HadiRj HadiRj - 3 months ago 5
Java Question

different of defining object inside and outside loops in Java

I was struggling with part of my code today to read some data from a file and add them to an object as its properties (I'm aware of how to add/read object in file without this hassle but wanted to do it this way) as below:

file is like this:

111,john,23.1
222,jack,22.5
234,adam,12.8


I was trying to read this file using following:

public ArrayList<Staff> LoadAllStaffs(){
ArrayList<Staff> staffs = new ArrayList<Staff>();
File file = new File(stafffile);
Staff tmpstaff = new Staff();
try {
BufferedReader inputfile = new BufferedReader(new FileReader(stafffile));
String tmp;
while((tmp = inputfile.readLine()) != null){
StringTokenizer st = new StringTokenizer(tmp , ",");
tmpstaff.setID(Integer.valueOf(st.nextToken()));
tmpstaff.setFirstName(st.nextToken());
tmpstaff.setSalary(Double.valueOf(st.nextToken()));
staffs.add(tmpstaff);
}
}
catch (IOException e) {
}
return staffs;
}


using println this output shown from the returned arraylist:

234,adam,12.8
234,adam,12.8
234,adam,12.8


I just moved the
Staff tmpstaff = new Staff();
inside the while loop and it shows what it should.

why this is happening? I read -even here- that defining variables (well, here its an Object ) inside or outside loops doesn't make any difference.

Answer

You are not creating a new Staff instance inside the loop, you are reusing the same instance for all the iterations. So, you overwrite the values and add the same object.

Move

Staff tmpstaff = new Staff();

to the first line inside the loop.

UPDATE: To address Vash's comment, the issue here is that can be explained as that, if you want to store 3 objects, you need to create such 3 objects. You can reuse the reference (the tmpstaff variable) and effectively where it is defined it is not important (as long as all references to it are in the same scope. But you must create the 3 objects, which means 3 new commands.

UPDATE 2: To put things simpler, the text I read -even here- that defining variables (well, here its an Object ) inside or outside loops doesn't make any difference. means that

File file = new File(stafffile);
Staff tmpstaff = null; // or simpler, Staff tmpstaff;
try {
   ...
   while((tmp = inputfile.readLine()) != null){
     tmpstaff = new Staff();
     ...

and

   while((tmp = inputfile.readLine()) != null){
     Staff tmpstaff = new Staff();
     ...

are equivalent.