简体   繁体   中英

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>(); 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 . 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. You would need to do an instanceof test on each element if you are looking for that type of functionality, example follows:

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();
}  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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