简体   繁体   English

如何创建一个包含 class 的任何子级列表的 class?

[英]How to create a class which holds list of any children of a class?

Java doubts: Java疑惑:

let's say I have a class named A. and I have its child classes as A1, A2, A3, etc. as shown below假设我有一个名为 A 的 class,我的子类为 A1、A2、A3 等,如下所示

eg例如

Class A 
{

}

Class A1 extends A {
}

Class A2 extends A{}
Class A3 extends A{}


Now I have another class which is ListA class.现在我有另一个 class,它是 ListA class。 this class has an attribute which is basically a list of any children of class A.这个 class 有一个属性,它基本上是 class A 的任何孩子的列表。

Class ListA<T> {
List<T> listOfChildren;

ListA(int n) {
//some how instantiate the above list based on the generic type.
}
}
}

I have used generic class because I think it is good way to tackle this use case.我使用了通用 class 因为我认为这是解决这个用例的好方法。 But any other suggestions will be helpful.但任何其他建议都会有所帮助。

Why not use this:为什么不使用这个:

List<? extends ClassA> myList=new ArrayList();
myList.add(myClass);//You will receive an error if you add anything that does not extend from ClassA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何找到实际上包含Java中元素的类 - How to find the class which actually holds the element in java 如何创建一个包含参数的JList? - How to create a JList which holds Parameters? 如何创建将返回扩展一个超类的任何类的List的方法 - How to create method that will return List of any class that extends one superclass 如何返回持有类java的对象 - How to return the object that holds a class java 找出哪个类/实例持有对打开文件的引用 - Find out which class/instance holds a reference to an open file 引用包含实体管理器的EJB的命名类的序列化 - Serialization of a named class with a reference to EJB, which holds the entity manager 正确的类,其中包含多个可关闭的资源 - Correct idiom for class which holds multiple closeable resources (初学者Java)Main方法是指单独的类中的一个保存数组的方法。 第二类的方法将如何设置? - (Beginner Java) Main method refers to a method in a seperate class which holds arrays. How would the method in the second class be set up? 将包含带有字段的 class 的列表转换为多个 arrays 的最快方法是什么? - - What is the fastest way to turn List that holds a class with fields into multiple arrays? - 如何创建内部子项而不创建另一个类? - How to create inner children without creating another class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM