java ArrayList contains different objects

前端 未结 5 1296
攒了一身酷
攒了一身酷 2020-12-09 06:28

Is it possible to create ArrayList list = new ArrayList();

I mean add obje

5条回答
  •  悲&欢浪女
    2020-12-09 06:51

    You can't specify more than one type parameter unfortunately, so you'll have to find a common superclass for your types and use that. An extreme case would be just using Object:

    List list = new ArrayList();
    
    
    

    Be careful that you will need to cast the result to the specific type that you need if you retrieve an item (to get full functionality, not just the common one):

    Car c = (Car)list.get(0); 
    

    提交回复
    热议问题