Creating instance list of different objects

前端 未结 7 1504
自闭症患者
自闭症患者 2021-02-04 08:17

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

List

        
7条回答
  •  春和景丽
    2021-02-04 09:05

    You could create a list of Object like List list = new ArrayList(). 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 list = new ArrayList();
    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
    
        

    提交回复
    热议问题