Creating instance list of different objects

arraylist, arrays, class, java, object

Solution

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("String");
list.add(Integer.valueOf(1));
list.add(new Employee());

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

Problem

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); ```

Original source

Related problems