Computing.Net > Forums > Programming > Object array in Java

Object array in Java

Reply to Message Icon

Original Message
Name: cunaz
Date: August 22, 2004 at 08:13:37 Pacific
Subject: Object array in Java
OS: Windows XP - Pro
CPU/Ram: 2400 Mhz/256 Mb RAM
Comment:

Hi guys, I've a question for you!
I have an object of this kind:
PosCoord(char amm, String moves, int[] coord), where coord is an array of coordinates. I created an array "scorpo" of PosCoord, length 29:
PosCoord [] scorpo = new PosCoord[29];
Now I write:
int [] c = {0,0,0};
for(int i=0;i<scorpo.length;i++)
{ scorpo[i] = new PosCoord(Protein.letterSeq[i], "NO", c);
}
where letterSeq is an array of char.
If I do:
scorpo[1].coord[1]=scorpo[0].coord[1]+1;
and I try to show the coords of scorpo[0] and scorpo[1] now I see that they are the same, while I want scorpo[1].coord[1] to be 1 and scorpo[0].coord[1] to be 0.
Why does it happen??And how can I solve the problem!!??Help me please!!
Thanx!!
-Mauri-


Report Offensive Message For Removal


Response Number 1
Name: Robert Crawford
Date: August 22, 2004 at 15:30:41 Pacific
Reply: (edit)

I may be a little rusty in Java, but I think the problem is that you are manipulating a common array. In your for loop when you are instantiating your PosCoord objects, you pass in a handle to the int[] array 'c'. Your code may be assuming that this array was copied into each of your PosCoord objects separately. However, each of your PosCoord objects only contains a handle (pass by refernce) to this common int[] array. Therefore, if somewhere in your code you try and load values into this array, all of your PosCoord objects will see this same value. This is probably why

scorpo[1].coord[1]=scorpo[0].coord[1]+1

have the same value: you're writing to the same location. Instead of passing in the handle to your int[] array, you actually need to copy the array contents, not just its location.

Try something like this:

for(int i=0;i<scorpo.length;i++)
{ scorpo[i] = new PosCoord(Protein.letterSeq[i], "NO", c[0],c[1],c[2]);
}

I'm not sure if this is compatible with your code, but the idea is that if you want to store different coordinates in each of your objects, they need different memory locations. You're code as is, doesn't do that.

Good Luck!


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: Object array in Java

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 5 Days.
Discuss in The Lounge