retroSpect
retroSpect

Reputation: 21

Why do I get the same value from different objects an an arrayList?

I add objects to my arraylist from a database table like this:

private void fillArray() {

    for (People temp : peopleList) {

        nameT = temp.getFirstName();
        IDT = temp.getUserid();

        users.add((new User(IDT, nameT) {

           @Override
            public String toString() {
                return ID + "," + name;
            }
      }));
   }
}

Wanting to display the elements of the objects in the arraList I separate them by overriding toString() and then using Scanner with the delimiter ",".

private void fieldSplitter(String object) {

    Scanner inline = new Scanner(object).useDelimiter(",");

    IDT = inline.next();
    nameT = inline.next();

    JOptionPane.showMessageDialog(null, IDT + " " + nameT, "Success", JOptionPane.INFORMATION_MESSAGE);

    IDT = null;
    nameT = null;

}

This should display all the different elements of each object. All I get is the last entry in my database table displayed every time even though there are 4 other entries. What have I done wrong?

Upvotes: 1

Views: 104

Answers (1)

Julien
Julien

Reputation: 2584

You should use the getters of your class User to have something cleaner :

users.add((new User(IDT, nameT) {
    @Override
    public String toString() {
        return getId() + "," + getName();
    }
}));

Upvotes: 1

Related Questions