Re: 關於HashSet 加入重覆物件卻成功加入的問題
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
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 6 之 9 篇):
java 近期熱門文章
PTT數位生活區 即時熱門文章