java – My arraylist is returning the same value on all "nodes"

Question:

This code should take all elements of a login.txt file and place them into a user array.

 public ArrayList<User> takeAll(){
    ArrayList<User> list = new ArrayList();
        User u = new User();
            String result = "";
            try {
            FileReader fr = new FileReader("C:\\Users\\vanes\\Documents\\WEBprog\\Archive\\login.txt");
            BufferedReader br = new BufferedReader(fr);
            while (br.ready()) {
                result = br.readLine() + "\n";
                String divider[] = new String[2];//split                
                divider = result.split(";"); //split
                u.setName(divider[0]);
                u.setLogin(divider[1]);
                u.setPassword(divider[2]);
               // System.out.println(u.getName()+";"+u.getLogin()+";"+u.getPassword());
                list.add(u);
            }
            br.close();
            fr.close();
        } catch (Exception ex) {
            System.out.println("Erro");
        }
    for (int i = 0; i < list.size(); i++) 
        System.out.println(list.get(i).getLogin());
    return list;    
}

I see it being added the way it's meant to be. However, when I try to print before the "return list", the result looks the same for all nodes. I would like to know where the error is.

It seems to me that it is not recording correctly inside the while. I've already tested the piece of code, in another place and it works perfectly, this part of the for, really, the error appears to be inside the while, but I can't see it.

Answer:

The problem is that you only create one User outside the loop:

        User u = new User();

And inside you change the data, but always from the same User :

                u.setName(divider[0]);
                u.setLogin(divider[1]);
                u.setPassword(divider[2]);

Then, if you uncomment the print, you will have the impression that it worked:

  // System.out.println(u.getName()+";"+u.getLogin()+";"+u.getPassword());

But at the end, when "going through the list" you will see that there are several references to the same User.

The solution is to create a new User() inside the loop and add it.

Scroll to Top