看板 java 關於我們 聯絡資訊
※ 引述《PsMonkey (痞子軍團團長)》之銘言: : 沒有學術根據的東西,請斟酌使用 or 開罵... : import java.util.ArrayList; : public class Foo { : public int hashCode(){ : System.out.println(super.hashCode()); : return super.hashCode(); : } : public boolean equals(Object obj){ : Foo other = (Foo) obj; : return other.hashCode()==this.hashCode(); : } : public static void main(String args[]){ : ArrayList<Foo> fooList = new ArrayList<Foo>(); : Foo f1 = new Foo(); : Foo f2 = new Foo(); : fooList.add(f1); : fooList.add(f2); : fooList.remove(f2); : } : } 首先, 不能依賴 super.hashCode(). 雖然 official JDK 是回傳 obj instance address 但我記得那不是規定. 另外, 這樣寫 equals, 倒不 如直接用 return this==obj 算了. 更重要的, 我覺得應該避免單為了這原因 override equals/hashcode. Foo 的 equals 還是應該放真的 equals 的比較. 不然以後真的需要 比較的話怎辦? 對於原 po 需要的, 我覺得寫 public static <T> void removeByReference(Collection<T> collection, <? super T> item) { for(Iterator<T> itr; itr.hasNext();) { T currentItem = itr.next(); if (currentItem == item) { itr.remove(); break; } } } 這樣比較好吧. 把 equals 和 hashCode 留著做它們更恰當的工作 } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 202.155.236.82
PsMonkey:囧> 只用官方 JDK 的傢伙 [逃] 07/14 10:56