我必須添加唯一元素到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