-1
class Users{    
    private LinkedHashSet<Users> userList=new LinkedHashSet<Users>();
    private String name;
        public Users(String name){
            this.name=name;
            userList.add(this);
        }
        public void iterateList(){
            for (Users user:userList){
                System.out.println(user.getName()); //NO OUTPUT WHEN CALLED
            }
        }
       public int getTotalUserCount(){
            return userList.size(); // OUTPUT IS 0
        }
}

I'm trying to add the instances of Users to userList when they are created. For some reason, when the userList is iterated through, I find that the objects weren't added.

Also, However, an accessor method getName() works when called on the object individually.

What am I doing wrong?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
SirVirgin
  • 153
  • 1
  • 3
  • 10

2 Answers2

1

Your problem is that your class design is broken. Your current code creates a new userList for each User instance, and that's not what you want. Instead the User class should not hold UserList but rather another class should handle that, and then when Users are created this other class gets places the User in the List.

Another option is to make the userList a static field, but this causes other potential problems as you will be throwing away the OOP baby with bathwater.

If you always want a User added tot he list when User's are created, then one way to achieve this and guarantee that it will happen is to create your User via a static factory method.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
0

Since userList is an instance variable, so it will be allocated new every time. You can mark userList as static variable so that it is available at class level.

Ankit Bansal
  • 4,962
  • 1
  • 23
  • 40