0

I am having problem displaying elements I have added to a List using Arrays utility class. The values stores are objects from a class People shown below

public class People {

private static Integer age;
private static String name;

public  People(String name,Integer age){

    this.age = age;
    this.name = name;
}

public Integer getAge(){
    return this.age;
}
public String getName(){
    return this.name;
}
@Override
public String toString(){
    return "name"+this.getName()+" Age"+ this.getAge();
}

}

The values are added into a List by the code below:

   List<People> myPeople = Arrays.asList(

        new People("Samuel Owino", 18),
        new People("Swale Mdohe", 12),
        new People("Joseph Wambwile", 48),
        new People("Samuel Werre", 18),
        new People("Swale Mdohe", 12),
        new People("Joseph Wambwile", 48)
);

The display code is as follows:

 myPeople.forEach(System.out::println);

Realised that the problem was using static access modifier on the instance variables in the bean class , age and name, when static is removed the method works perfectly. Thanks for the referencing.

Samuel Owino
  • 747
  • 1
  • 12
  • 24

2 Answers2

1

You have the member variables set as static, they should be instance level:

private Integer age;
private String name;

Otherwise each addition to the list overwrites the shared state of the People object.

I suspect that as the variables are passed into the constructor that you mean to use final not static.

Lee
  • 738
  • 3
  • 13
1

To have the last item of your list, you can do this:

System.out.println(myPeople.get(myPeople.size() - 1));
Valentin Grégoire
  • 1,110
  • 2
  • 12
  • 29