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
Listor aSet. For instance:Now when you say this:
That is an invalid assumption. The collection will hold any object that extends
Superhowever you cannot arbitrarily cast each element into whatever you want. You would need to do aninstanceoftest on each element if you are looking for that type of functionality, example follows:Scope as need be.
Now on the point of Vlad:
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: