Creating instance list of different objects

前端 未结 7 1475
自闭症患者
自闭症患者 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:16

    I see that all of the answers suggest using a list filled with Object classes and then explicitly casting the desired class, and I personally don't like that kind of approach.

    What works better for me is to create an interface which contains methods for retrieving or storing data from/to certain classes I want to put in a list. Have those classes implement that new interface, add the methods from the interface into them and then you can fill the list with interface objects - List newInterfaceList = new ArrayList<>() thus being able to extract the desired data from the objects in a list without having the need to explicitly cast anything.

    You can also put a comparator in the interface if you need to sort the list.

提交回复
热议问题