2014-09-02 80 views
0

我想比较两个数组使用Object重写的方法。我应该把对象参数投到ListInterface,我似乎无法弄清楚发生了什么。任何帮助,将不胜感激。覆盖对象等于方法

public class AList<T extends Comparable> implements ListInterface <T> { 

    private T[] list; 
    private int length; 
    private static final int MAX_SIZE = 50; 

    public AList() 
    { 
     this(MAX_SIZE); 
    } 
    public AList(int maxSize) 
    { 
     length = 0; 
     list = (T[]) new AList[maxSize]; 
    } 

    public boolean equals(Object other) 
    { 

     boolean results = true; 
     if (list.length == ((ListInterface<T>) other).getLength()) 
     { 
      for(int i = 0; i < list.length; i++) 
      { 
       if(list[i].equals((ListInterface<T>)other[i])) 
        results = true; 
      } 
     } 
     return results; 
    } 
+1

请提供更多关于什么是错的或者你是如何卡住的细节。请注意,我会首先检查null,然后在检查其他内容之前检查引用是否相等。即if(other == null)返回false;'和if(other == this)返回true;'然后我会在* cast之前检查instanceof *。 – 2014-09-02 02:34:19

+0

AList 的一个实例应该可能等于实现ListInterface 的不同类的实例吗?这可能会违反.equals(Object o)不变量,如果a.equals(b)为true,则b.equals(a)也应该为true。 – Mshnik 2014-09-02 02:34:48

回答

0

如果other一个ListInterface<T>?什么将

myListInterface.equals(new StringBuilder()); 

做? (答案是抛出一个InvalidCastException什么的)。铸造只能改变原始物的类型,例如intboolean它是而不是能够改变物体的类型。将一个数组转换为列表并不会使它成为一个列表,它只是使得每次尝试调用该对象所没有的列表方法时都会引发错误。这通常表明你的多态设计不好,但这种方法是个例外。这意味着您首先需要使用instanceof

覆盖equals很难。尝试从Eclipse或IntelliJ中自动生成一个以查看进入其中的工作,或者在线查找默认覆盖实现。

+0

这里是我的老师的一些建议。 “这个方法应该覆盖Object类的equals方法,方法头应该反映这个,你需要将参数从Object转换为ListInterface。”第一个数组来自实现ListInterface 的AList类。第二个数组是在主测试中创建的方法。 正在比较的两个数组如下所示。 T [] list =(T [])new AList [maxSize] AList otherNames = new AList (); – user3242607 2014-09-02 03:20:32

4

看来你的equals方法试图检查对象封装的两个数组是否包含相同的对象。 Arrays.deepEquals(T [] t1,T [] t2)可能会有所帮助。

public boolean equals(Object other) 
{ 
    if(other == null || ! (other instanceof AList<T>)) 
     return false; 
    AList<T> a = (AList<T>)other; 
    return Arrays.deepEquals(list, a.list); 
}