【发布时间】:2013-05-10 03:04:17
【问题描述】:
我的任务是重写equals()方法。我对使用Stack12<E> that = (Stack12<E>)o; 和o instanceof Stack12 有一些顾虑。我想知道他们是不是不好的做法,尤其是我在 for 循环中使用 that 的方式对我来说有点不合适。
还有其他方法可以将此类与其他对象进行比较吗?还是我的比较方法足够稳健?
public boolean equals(java.lang.Object o){
if(o == this) return true;
if(o == null || !(o instanceof Stack12)){
return false;
}
Stack12<E> that = (Stack12<E>)o;
if(this.size != that.size || this.capacity != that.capacity ){
return false;
}
for(int i = 0; i < this.size; i++){
if( that.stack[i] != this.stack[i] ){
return false;
}
}
return true;
}
【问题讨论】:
-
我对将对象转换为泛型类型感到不舒服。而且我认为我在某处使用 instanceof 在 Java 中阅读是一种不好的做法。
-
我要补充的唯一警告是,无论何时覆盖
equals(...),您还需要覆盖hashCode()。糟糕,我确实看到了一个主要问题——已发布答案。