我想使用泛型概念,创建一个需要接受不同类型对象的ArrayList,所以我想创建一个名为ObjectType
的空类,并通过"Person and Animal
"类继承它,并想创建如下所示的ArrayList
List<? extends ObjectType> list=new ArrayList<Persons>();
但它不起作用,解决方案是什么?
通常,我会尽可能使用interface
而不是类,因为它更简单、更灵活。
你能写的是
interface ObjectType { }
class Animal implements ObjectType { }
class Person implements ObjectType { }
List<ObjectType> objects = new ArrayList<>();
这可能不会达到你的预期,但你如何解决这取决于你需要列表做什么。