Creating instance list of different objects


I'm tring to create an arraylist of different class instances. How can I create a list without defining a class type? (<Employee>)

List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee());
Employee employee = employees.get(0);

This question is tagged with java arrays class object arraylist

~ Asked on 2012-06-17 17:54:55

The Best Answer is


You could create a list of Object like List<Object> list = new ArrayList<Object>(). As all classes implementation extends implicit or explicit from java.lang.Object class, this list can hold any object, including instances of Employee, Integer, String etc.

When you retrieve an element from this list, you will be retrieving an Object and no longer an Employee, meaning you need to perform a explicit cast in this case as follows:

List<Object> list = new ArrayList<Object>();
list.add(new Employee());

Object retrievedObject = list.get(2);
Employee employee = (Employee)list.get(2); // explicit cast

~ Answered on 2012-06-17 17:55:58


List<Object> objects = new ArrayList<Object>();

objects list will accept any of the Object

You could design like as follows

public class BaseEmployee{/* stuffs */}

public class RegularEmployee extends BaseEmployee{/* stuffs */}

public class Contractors extends BaseEmployee{/* stuffs */}

and in list

List<? extends BaseEmployee> employeeList = new ArrayList<? extends BaseEmployee>();

~ Answered on 2012-06-17 17:56:22

Most Viewed Questions: