[英]Overriding Object equals method
我正在尝试使用我覆盖的Object equals方法比较两个数组。 我应该将对象参数转换为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;
}
看来您的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);
}
并且如果other
不是 ListInterface<T>
? 会怎样
myListInterface.equals(new StringBuilder());
做? (答案是抛出InvalidCastException
东西)。 强制转换只能更改基本类型的事物类型,例如,将int
更改为boolean
它不能更改对象的类型。 将数组强制转换为列表并不能使其成为列表,而只是使它每次尝试调用对象没有的list方法时都将引发错误。 通常这表明您的多态设计不正确,但是这种方法是个例外。 这意味着您需要首先使用instanceof
。
重写equals
是很难的。 尝试从Eclipse或IntelliJ自动生成一个,以查看其中的工作,或在线查找默认的覆盖实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.