我有這個代碼:@Overridepublic boolean equals(Object obj) { System.out.println("equals called"); if(this == obj) { System.out.println("THIS object is the same as OBJ"); return true; } System.out.println("obj.getClass() is " + obj.getClass()); System.out.println("this.getClass() is " + this.getClass()); if ((obj == null) || (obj.getClass() != this.getClass())) { return false; } double objOrbitalPeriod = ((HeavenlyBody) obj).getOrbitalPeriod(); return this.orbitalPeriod == objOrbitalPeriod;}@Overridepublic int hashCode() { return 0;}在主要代碼是:private static Set<Planet> solarSystem = new HashSet<>();public static void main(String[] args) { Planet planet = new Planet("Earth", 365.0);` solarSystem.add(planet); solarSystem.add(planet);}有人可以解釋為什么它不打印任何東西嗎?我希望它應該打?。?"equals called"和(因為它是重復的):"THIS object is the same as OBJ"但似乎發生了一些我無法理解的事情。
2 回答

有只小跳蛙
TA貢獻1824條經驗 獲得超8個贊
嗯,HashSet是使用HashMap. 在 in 的實現put中HashMap,它使用適當的散列定位節點,然后檢查:
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
這意味著它首先檢查對象身份,只有當對象不相同時,它才會調用該equals方法。由于您的對象是相同的,因此equals不會調用該方法。

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
在HashMap (a的內部實現HashSet)的源代碼中,有一個if條件,表示如果兩個key是同一個引用,就不需要調用equals。
...
if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
break;
...
添加回答
舉報
0/150
提交
取消