我必须添加唯一元素到ArrayList
。我怎样才能为此覆盖equals
方法?我想是这样的:如何使用equals()创建独特元素的ArrayList
public boolean equals (Object in) {
if(in == null) {
return false;
}
else if(in instanceof UniqueFruits) {
// ?? check whether the newly added element exists or not
return true;
}
else {
return false;
}
}
如何检查新添加的元素是否存在?我必须检查水果名称。
为了做到这一点,你必须重写'equals'和'hashCode'方法。 – 2012-08-09 04:00:24
但是如何?我需要检查部分的代码。 – 2012-08-09 04:02:28
您必须比较里面的属性值,你的'如果(在的instanceof UniqueFruits){...}'代码返回true或false,这取决于你的规则,像水果的名字或任何你想/需要 – 2012-08-09 04:03:33