作者lin1000 (你是研究生吗)
看板java
标题Re: 关於HashSet 加入重覆物件却成功加入的问题
时间Thu Apr 27 22:48:36 2006
Sorry to type in English.
It seems to be different from your result
My testing result shows only following output without the equals function
Anyone know why?
Console output:
-----------------------------------
Do Add A Element
Call hashCode()
Do Add A Element
Call hashCode()
Do Add A Element
Call hashCode()
-------------------------------------
Running Codes
-------------------------------------
import java.util.HashSet;
public class TasteHashSet {
public static void main(String[] args) {
Object o = new Object() {
public int hashCode() {
System.out.println("Call hashCode()");
return super.hashCode();
}
public boolean equals(Object obj) {
System.out.println("Call equals()");
return super.equals(obj);
}
};
Object o1 = new Object() {
public int hashCode() {
System.out.println("Call hashCode()");
return super.hashCode();
}
public boolean equals(Object obj) {
System.out.println("Call equals()");
return super.equals(obj);
}
};
HashSet hash = new HashSet() {
public boolean add(Object o) {
System.out.println("Do Add A Element");
return super.add(o);
}
};
hash.add(o);
hash.add(o);
hash.add(o1);
}
}
※ 引述《Bluesky7 ()》之铭言:
: ※ 引述《qrtt1 (隐者)》之铭言:
: : import java.util.HashSet;
: : public class TasteHashSet {
: : public static void main(String[] args) {
: : Object o = new Object() {
: : public int hashCode() {
: : System.out.println("Call hashCode()");
: : return super.hashCode();
: : }
: : public boolean equals(Object obj) {
: : System.out.println("Call equals()");
: : return super.equals(obj);
: : }
: : };
: : HashSet hash = new HashSet() {
: : public boolean add(Object o) {
: : System.out.println("Do Add A Element");
: : return super.add(o);
: : sda }
: : };
: : hash.add(o);
: : }
: : }
: : 俺好奇到底谁先呼叫, 是equals还是hashCode
: : 写了程式测了一下, 结果..hahaha
: :) 我测了一下 当插入第一个element的时候 只会call 到hashcode()
: 之後每次插入element时
: hashcode() 跟equals(Object)都会 call到
: equals回传true 且hashcode()传出相同整数时候
: HashSet才会视作相同物件
: 谢谢各位
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 202.178.206.10