我同時覆蓋hashCode()和equals()方法,但我不修改重寫方法內部的任何物件。重寫的hashCode()和equals()方法
@Override public int hashCode() { int hash = 7; hash = 67 * hash + Objects.hashCode(this.model); hash = 67 * hash + this.year; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PC other = (PC) obj; if (!Objects.equals(this.model, other.model)) { return false; } if (this.year != other.year) { return false; } return true; }
我創建2個相同的對象:
PC One = new PC(); One.setModel("HP"); One.setYear(2013); PC Two = new PC(); Two.setModel("HP"); Two.setYear(2013);
我比較這些2個對象:
if (One.equals(Two)) { System.out.println("They are the same objects!"); } else { System.out.println("They are different objects!"); }
的結果是: 「他們是同一對象」 。但是,如果我不覆蓋這兩種方法,結果將是:「它們是不同的對象!」。 因爲hashCode對於每個對象都是唯一的(我想),我期望它的結果是:「它們是不同的對象!」。 問:爲什麼?
「PC」的超類是什麼? – 2014-10-07 18:33:22
你的重寫「equals」是什麼樣的? – Eran 2014-10-07 18:33:41
@PatriciaShanahan,Class Object,意思是PC沒有我定義的超類。 – Insanovation 2014-10-07 18:35:57