0

我目前有两个从中创建对象的类。我需要一个数组来存储对这些对象的引用(指针)。数组应该是什么类型的?

ArrayList<Class1> visableObjs = new ArrayList<Class1>();

当然只会存储指向来自 Class1 的对象的指针。如果我有一个来自 Class2 的对象,我可以将它的指针存储在同一个数组中吗?

4

3 回答 3

1

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.

于 2013-10-30T14:27:26.837 回答
0

我们可以这样做。如果对象来自不同的类,这根本不是一个好习惯。

ArrayList<Object> visableObjs = new ArrayList<Object>();

或者

ArrayList visableObjs = new ArrayList();
于 2013-10-30T14:26:04.647 回答
0

您也许可以使用泛型来创建一个 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 来测试它。但这个想法应该很清楚。

于 2013-10-30T17:50:44.073 回答