Trying a simple example where I am entering the data through the console and adding them to a List. But the values of the last name,age entered repeats itself in the List.
private List<User> getData() throws IOException{
User user=new User();
List<User> userList=new ArrayList<User>();
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<2;i++){
System.out.println("Enter name,age:");
String values=reader.readLine();
String[] value=values.split(",");
user.setName(value[0]);
user.setAge(value[1]);
userList.add(user);
}
return userList;
}
On printing the userList, its seems that the list is populated with final values I entered through the console.
Example,
Enter name,age: rickesh,22
Enter name,age: john,21
Contents of List: [john 22,john 22]
public class User {
private String age;
private String name;
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Create new User in a for loop.