Creating instance list of different objects

前端 未结 7 1503
自闭症患者
自闭症患者 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 08:54

    I believe your best shot is to declare the list as a list of objects:

    List anything = new ArrayList();
    
    
    

    Then you can put whatever you want in it, like:

    anything.add(new Employee(..))
    

    Evidently, you will not be able to read anything out of the list without a proper casting:

    Employee mike = (Employee) anything.get(0);
    

    I would discourage the use of raw types like:

    List anything = new ArrayList()
    

    Since the whole purpose of generics is precisely to avoid them, in the future Java may no longer suport raw types, the raw types are considered legacy and once you use a raw type you are not allowed to use generics at all in a given reference. For instance, take a look a this another question: Combining Raw Types and Generic Methods

    提交回复
    热议问题