Reputation: 1092
I currently have two classes that I create objects from. I need an array that will store references (pointers) to these objects. Of what type should the array be?
ArrayList<Class1> visableObjs = new ArrayList<Class1>();
Will of course only store pointers to objects that stem from Class1. If I had an object from Class2 could I store it's pointer in the same array?
Upvotes: 0
Views: 1216
Reputation: 3058
You could perhaps use generics to create a Choice class to hold a reference to one or other type, but not both:
public final class Choice<A,B> {
private final A a;
private final B b;
private final boolean isA;
private Choice(A a, B b, boolean isA) {
this.a = a; this.b = b; this.isA = isA;
}
public static <A,B> Choice<A,B> ofA(A a) {
return new Choice<>(a, null, true);
}
public static <A,B> Choice<A,B> ofB(B b) {
return new Choice<>(null, b, false);
}
public boolean isA() { return isA; }
public A getA() {
if(!isA) throw new IllegalStateException("Not a!");
return a;
}
public boolean isB() { return !isA; }
public B getB() {
if(isA) throw new IllegalStateException("Not b!");
return b;
}
// Purely for demo purposes...
public static void main(String[] args) {
Choice<Integer,String> ich = Choice.ofA(42);
Choice<Integer,String> sch = Choice.ofB("foo");
// This is why the isA is included; so we can tell a null A from a null B.
Choice<Integer,String> nil = Choice.ofA(null);
//
List<Choice<Boolean,String>> xs = new ArrayList<Choice<Boolean,String>>();
xs.add(Choice.ofA(true));
xs.add(Choice.ofB("neep"));
}
}
This should work for two unrelated classes. Or for two out of many related subclasses, where you want to restrict to only those two possibilities - and not any subclass of a more general class/interface.
Such a class should probably be extended to properly implement equals()/hashCode(), toString(), etc. (For some definition [documented] of 'properly'.)
Caveat: this may not compile first try - I don't have a javac handy to test it. But the idea should be clear.
Upvotes: 0
Reputation: 920
if you mean that the objects you store are instances of those two classes, you should make those classes inherit from a (custom?) class or interface and use that class/interface as the type to store in your array.
Upvotes: 1
Reputation: 26094
We can do like this. Its not good practice at all if objects are from different classes.
ArrayList<Object> visableObjs = new ArrayList<Object>();
or
ArrayList visableObjs = new ArrayList();
Upvotes: 0