I am trying to create a list of objects like this :
List<Employee> employee= new ArrayList<Employee>();
Set a key and value for this like this :
Employee emp = new Employee();
emp.setKey("John");
emp.setValue("305");
emp.setKey("David");
emp.setValue("790");
And finally, I put this on a list :
employee.add(emp);
When I print, it gives me only last entry :
for(Employee em : employee){
System.out.println(em.getKey());
}
It only give me "David " as a result and not "John" and "David"
Can somebody tell me how should I do this ?
You have created only one object:
Employee emp = new Employee();
emp.setKey("John");
emp.setValue("305");
Employee emp1 = new Employee();
emp1.setKey("David");
emp1.setValue("790");
employee.add(emp);
employee.add(emp1);
Now run the for loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With