Adding objects to an ArrayList

My intention was to create an ArrayList of "Employee" objects. Each "Employee" has a name and a id. My Employee class looks like this:

package test;

publicclass Employee{

private String name =null;

privateint id = 0;

public Employee(){

}

publicvoid setName(String n){

name = n;

}

public String getName(){

return name;

}

publicvoid setID(int i){

id = i;

}

publicint getID(){

return id;

}

}

Then I have a main class which is suppose to set the names and id's then add the object to the array list

package test;

import java.util.ArrayList;

publicclass Main{

private Employee e =new Employee();

private ArrayList<Employee> employees =new ArrayList<Employee>();

public Main(){

generateEmployees();

for(int i = 0; i < employees.size(); i++){

System.out.println(employees.get(i).getName());

}

}

publicvoid generateEmployees(){

//Add Joe

e.setName("Joe");

e.setID(1);

employees.add(e);

//Add Bob

e.setName("Bob");

e.setID(2);

employees.add(e);

}

publicstaticvoid main(String[] args){

new Main();

}

}

But when I run it, rather than seeing Joe and Bob is see Bob and Bob, what am I doing wrong?

[3245 byte] By [SidewinderXa] at [2007-11-26 18:14:18]
# 1

You are not adding two Employee objects to the List but the same object twice (or more accurately adding the reference to the one object to the list twice).

employees.add(new Employee("Joe"));

employees.add(new Employee("Bob"));

You will need to change the Employee constructor.

floundera at 2007-7-9 5:47:39 > top of Java-index,Java Essentials,Java Programming...
# 2

Or if you want to keep Employee as is.

e.setName("Joe");

e.setID(1);

employees.add(e);

e = new Employee(); // note: e now refers to a NEW object.

e.setName("Bob");

e.setID(2);

employees.add(e);

floundera at 2007-7-9 5:47:39 > top of Java-index,Java Essentials,Java Programming...
# 3

What flounder writes is true. I would also add: get rid of Main's field e -- it will only get you into trouble. A Main object has a list of employees: that makes sense. A Main object has a list of employees and a distinguished employee: that doesn't make sense.

If you had been able to write the following, your life would have been easier:

employees.add(new Employee("Joe",1));

employees.add(new Employee("Bob",2));

DrLaszloJamfa at 2007-7-9 5:47:39 > top of Java-index,Java Essentials,Java Programming...