I’m creating an Array to hold a number of objects which all implement a given interface. Much of the time, it won’t matter what the subtype of the Object is, but, occasionally it will and I want to add some methods to get those subtypes for when required eg getA(), getB() etc.
I’m thinking that indexing them by a number for each subtype would be the quickest way to do this, although it would require a collection class that allows for duplicate keys:
private Array<SuperInterface> objects;
public Array<A> getA() {
return objects.get(0); //0 being the index number for objects of type A
}
the alternative is simply to iterate through and create a new Array of that type:
private Array<SuperInterface> objects;
public Array<A> getA() {
Array<A> a = new Array<A>();
for (SuperInterface super : objects) {
if (super instanceof A) {
a.add(super);
}
}
return a;
This, however, seems to me to be the least efficient approach.
So, my questions are:
-
Do you agree with my assessment regarding efficiency? If not, what would you suggest?
-
Are you aware of a good Map implementation that allows duplicate keys?
I’m aware that Google’s Guava includes a MultiMap implementation, but it seems overkill to include a library simply to use one class.
Hope that all makes sense!