Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Object not saving in Array of Objects....

well...my problem is im storing values from a file into a regular object called Students. I then take that information and assign it to an array of Student objects.


try
{
fileReaderIn = new FileReader("A2Q1in.txt");
fileIn = new BufferedReader(fileReaderIn);

testLine = fileIn.readLine();
while(testLine != null)
{
String[] result = testLine.split("\\s+");

//im previously aware of what the input file looks like
students1.setALL(result[1], result[0], result[2]);
students1.setGPA(Double.parseDouble(result[3]));


students4[counter] = students1;//if i test this, i find that the values are being store into the array
//----------------
System.out.println("Counter--> " + counter);
counter++;
testLine = fileIn.readLine();
}
fileIn.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
ioe.printStackTrace();
}
//----------------

System.out.println("counter --> " + counter);
students = new Student[counter];
for(int j = 0; j < counter; j++)
{
students[j] = students4[j];// printing this will print the same person from each entry
}

return students;

now somewhere between the dashed lines, all of my values in my array of objects become one and the same, and whether by coincience or logic problems they all are the last bit of info retrived from the file.

im not sure what it is im doing wrong but if anyone could help me with arrays of objects that would be much appreciated. Thx
[1720 byte] By [TriviuM] at [2007-11-11 7:56:10]
# 1 Re: Object not saving in Array of Objects....
students4[counter] = students1;
With this line you are setting every element in students 4 to point to student1. There is only one student1, whos values you keep changing, but which is pointed to by all elements of the student4 array.

Each element of student4 should point to a different student object. One way to do this is create a new student object for each pass through your readLine() loop.

Remember, an array is a collection of object references. You can make them all point to the same object if you wish, but it's more useful here if they each point to a different student object.
Laszlo at 2007-11-11 22:36:53 >