2013-10-30 35 views
0

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

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

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

+0

你可以让这两个类都实现一个接口,或者让两个类共享一个共同的父类。然后,您可以将列表的类型设置为界面或公用父项的类型。哪一个对你正在做的事情最有意义。 –

回答

1

,如果你的意思是你存储的对象是那些两个类的实例,你应该让这些类从继承(习惯吗?)类或接口,并使用类/接口作为存储在你的数组中的类型。

+0

Class1实现myClass,Class2实现myClass,ArrayList Voidpaw

+0

请使用Java命名约定。 –

+0

你*不应该*使你的两个类从一个通用的超类(或接口)继承,除非它们真的*是有意义的 - 这种超类型的实例。你当然不应该这样做*只要你可以把它们放在同一个集合中*。如果你这样做,你就会混淆类型和需要聚合异构集合中的元素。 – Paul

0

我们可以这样做。如果对象来自不同的类别,它根本就不是很好的练习。

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

ArrayList visableObjs = new ArrayList(); 
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方便测试它。但这个想法应该清楚。

+0

顺便说一下。这个想法来自Scala类:http://www.scala-lang.org/api/current/#scala.util.Etil – Paul

相关问题