Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this method returning an ArrayList with all the same objects? JAVA

I have a class called User and a file called Users.csv, like below:

User class:

public class User
{
private String name;
private String rg;
private String type;

public String getName()
{
    return name;
}

public String getRg()
{
    return rg;
}

public String getType()
{
    return type;
}

public void setName(String n)
{
    name = n;
}

public void setRg(String r)
{
    rg = r;
}

public void setType(String t)
{
    type = t;
}
}

Users.csv:

a,b,c
d,e,f
as,d,cf

Also, I have a class called test, which implements a single method:

test class:

public class test
{
public ArrayList<User> readUsers(String path) throws IOException //read all users from file and returns an ArrayList
{       
    ArrayList<User> list = new ArrayList<User>();
    String[] str;
    User u = new User();
    BufferedReader buffRead = new BufferedReader(new FileReader(path));
    String line = buffRead.readLine(); 
    while(line != null)
    {
            str = line.split(",");
            u.setName(str[0]); //sets each field read to "u"
            u.setRg(str[1]);
            u.setType(str[2]);
            list.add(u); //adding user to the list to be returned
            line = buffRead.readLine(); //reading next register
    }
buffRead.close();
return list;
}
}  

The problem is in the method readUsers(). It is returning me an ArrayList where every element is the same, and they are the one at the last line of Users.csv.
Any tip why it is happening? I can't figure it out...

like image 797
Quik19 Avatar asked May 29 '15 01:05

Quik19


2 Answers

How many times do you call new User()? That's how many User objects you've created: exactly one, and you do this once before the loop.

Solution, call this inside of the loop -- this way you create a new User for each item that you add to the list.

like image 122
Hovercraft Full Of Eels Avatar answered Sep 28 '22 22:09

Hovercraft Full Of Eels


You've only created a single instance of User and are simply changing it's properties. You will need to create a new instance of User for each entry in the CSV file

//User u = new User();
//...
while(line != null)
{
        str = line.split(",");
        User u = new User();
        u.setName(str[0]); //sets each field read to "u"
        u.setRg(str[1]);
        u.setType(str[2]);
        list.add(u); //adding user to the list to be returned
        line = buffRead.readLine(); //reading next register
}
like image 30
MadProgrammer Avatar answered Sep 28 '22 22:09

MadProgrammer