我同时覆盖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