我目前有两个类创建对象。我需要一个数组来存储这些对象的引用(指针)。数组应该是什么类型?存储对不同类的对象的引用
ArrayList<Class1> visableObjs = new ArrayList<Class1>();
当然只会存储指向源自Class1的对象的指针。如果我有Class2的对象,我可以将它的指针存储在同一个数组中吗?
我目前有两个类创建对象。我需要一个数组来存储这些对象的引用(指针)。数组应该是什么类型?存储对不同类的对象的引用
ArrayList<Class1> visableObjs = new ArrayList<Class1>();
当然只会存储指向源自Class1的对象的指针。如果我有Class2的对象,我可以将它的指针存储在同一个数组中吗?
我们可以这样做。如果对象来自不同的类别,它根本就不是很好的练习。
ArrayList<Object> visableObjs = new ArrayList<Object>();
或
ArrayList visableObjs = new ArrayList();
也许你可以使用泛型创建Choice类召开参考一个或其他类型,但不能同时:
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"));
}
}
这应该有两个不相关的类工作。或者对于相关的子类中的两个,您只想限制这两种可能性 - 而不是更普通的类/接口的任何子类。 (有关的 '正常' 一些定义[记录])
这样的类可能应该被扩展到正确实现equals()/ hashCode()方法,的toString()等
警告:这可能不编译第一次尝试 - 我没有javac方便测试它。但这个想法应该清楚。
顺便说一下。这个想法来自Scala类:http://www.scala-lang.org/api/current/#scala.util.Etil – Paul
你可以让这两个类都实现一个接口,或者让两个类共享一个共同的父类。然后,您可以将列表的类型设置为界面或公用父项的类型。哪一个对你正在做的事情最有意义。 –