Populating an instance array in Java

Status
Not open for further replies.

memphis_1220

Limp Gawd
Joined
Aug 28, 2004
Messages
499
I am a little confused as to why this instance array is not working out as planned. Maybe someone could shed some light on this problem.

I have a class called Piece with a bunch of variables including int colour and piece.
32 of these have been declared and initialised using an instance array:

Code:
Piece[] piece_list = new Piece[32];

for(int i=0;i<32;i++)
{
	piece_list[i]=new Piece();
}

In order to populate these I have used a simple for loop that iterates through each one and sets the values accordingly:

Code:
for(int i=0;i<32;i++)
{
	if(i<16)
		piece_list[i].colour=1;
	else
		piece_list[i].colour=0;

	if((i>7)&&(i<24))
		piece_list[i].piece=5;
	else
		piece_list[i].piece=4;
}

So the first 16 "Piece"'s should have a colour value of 1 and the rest 0. Although each one is actually being set as 0.

Similarly, "Piece"'s from 8 and 23 inclusive should have a piece value of 5 and the rest 4. Although each one is being set as 4.

Does anyone know why this is happening?
 
I understand what is happening now, but not why it is happening.

The last iteration is i=31 and it is setting every colour value to what is appropiate for the last entry of the array.

Should it be doing this? I thought that an instance/object/class array would be a way of keeping track of many objects, each with their OWN variable values.
 
Stupid me :(

I created the class a while back and have only just noticed that I declared the two variables as static. So what I was trying to do above was correct. I was beginning to doubt my implementation of basic Java programming.

Corrected and locked.
 
Status
Not open for further replies.
Back
Top