简体   繁体   English

Java-包含一组相同超类的不同子类的数据结构

[英]Java - data structure to contain a set of different subclasses of the same superclass

I need to have some sort of data structure that can contain heterogenous subclasses of the same superclass, all of which I have implemented myself. 我需要某种数据结构,其中可以包含同一超类的异构子类,而我自己都实现了所有这些子类。

So far, I am attempting to have an ArrayList<SuperClass> list = new ArrayList<SuperClass>(); 到目前为止,我正在尝试使用ArrayList<SuperClass> list = new ArrayList<SuperClass>(); and then, I am assuming I will be able to cast each slot of list into either of the subclasses, but this is not working out so well. 然后,我假设我将能够将列表的每个位置转换为两个子类中的任何一个,但是效果不是很好。

I need an efficient way to do the aforementioned. 我需要一种有效的方法来进行上述操作。

Thanks! 谢谢!

You can do it with any data structure that exists, I would recommend a List or a Set . 您可以使用任何存在的数据结构来做到这一点,我建议您使用ListSet For instance: 例如:

Collection<Super> supers = new ArrayList<Super>();  

Now when you say this: 现在,当你这样说:

I am assuming I will be able to cast each slot of list into either of the subclasses, 我假设我将能够将列表的每个位置转换为任何一个子类,

That is an invalid assumption. 那是一个无效的假设。 The collection will hold any object that extends Super however you cannot arbitrarily cast each element into whatever you want. 该集合将保留扩展Super所有对象,但是您不能将每个元素任意转换为所需的任何对象。 You would need to do an instanceof test on each element if you are looking for that type of functionality, example follows: 如果要寻找这种类型的功能,则需要对每个元素进行一次instanceof测试,示例如下:

for(Super currentSuper : supers)  
{  
    if(currentSuper instanceof SubA)  
    {  
         SubA subA = (Suba) currentSuper);  
         // do stuff with subA
    }  
    else if(currentSuper instanceof SubB)  
    {  
         SubB subB = (SubB) currentSuper);  
         // do stuff with subB
    } 
}  

Scope as need be. 范围视需要而定。

Now on the point of Vlad: 现在说到弗拉德:

and much better design would be not to test what the actual class is, but just to call a virtual method, which will do the right thing in any case 更好的设计将不是测试实际的类,而只是调用虚拟方法,这在任何情况下都会做正确的事情

If you can guarantee the functionality of all potential sub-classes and have no issues with people overriding your classes (in the event you haven't marked them final) you do not need to do the instance of test. 如果您可以保证所有潜在子类的功能,并且对覆盖您的类的人员没有任何问题(如果您没有将其标记为最终类),则无需执行测试实例。 Instead your code could be as simple as: 相反,您的代码可能很简单:

for(Super currentSuper : supers)  
{  
    currentSuper.doSomethingNifty();
}  

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM