Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating List of Objects in JAVA

Tags:

java

arraylist

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 ?

like image 853
JustStartedProgramming Avatar asked May 04 '26 20:05

JustStartedProgramming


1 Answers

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

like image 52
spandey Avatar answered May 07 '26 10:05

spandey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!