我重写了 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);
我比较了这两个对象:
if (One.equals(Two)) { System.out.println("They are the same objects!"); } else { System.out.println("They are different objects!"); }
结果是:“它们是相同的对象!”。但是,如果我不重写这两种方法,结果将是:“它们是不同的对象!”。 因为 hashCode 对于每个对象都是唯一的(我想),所以我期望结果是:“它们是不同的对象!”。 问:为什么?
最佳答案
Object
的默认equals
实现使用实例的引用地址。两个 对象
仅当它们位于内存中的相同位置时才相等。
如果您不重写 equals
,那么您将获得该实现。
此外,此行为与 hashCode
无关,因为您没有调用 hashCode
。如果您直接调用 equals
,则不会使用 hashCode
。 hashCode
与HashMap
一样,一般用于数据结构中。
关于java - 覆盖 hashCode() 和 equals() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26242832/