作者adrianshum (Alien)
看板java
标题Re: [问题] 要如何以reference的方式remove list的 …
时间Tue Jul 14 10:37:02 2009
※ 引述《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
1F:推 PsMonkey:囧> 只用官方 JDK 的家伙 [逃] 07/14 10:56