實體類 class Point { private int x; private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; ...
實體類
class Point { private int x; private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public boolean equals(Object obj) { if (this == obj)//ref相等 { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } Point that = (Point) obj; return x == that.x && y == that.y;//對比值 } }
以上代碼重寫了equals。
比較
@Slf4j public class EqualsHashDemo { public static void compare() { Point a = new Point(); a.setX(1); a.setY(2); Point b = new Point(); b.setX(1); b.setY(2); log.info("a.equals(b) is " + a.equals(b)); } }
這個時候輸出是true
把對象裝入hashset進行比較
@Slf4j public class EqualsHashDemo { public static void compare() { Point a = new Point(); a.setX(1); a.setY(2); Point b = new Point(); b.setX(1); b.setY(2); log.info("a.equals(b) is " + a.equals(b)); HashSet<Point> points=new HashSet<>(); points.add(a); log.info("points.contains(b) is " + points.contains(b)); } }
輸出
a.equals(b) is true points.contains(b) is false
這裡就是因為沒有重寫hashcode導致的。沒有重寫,預設使用的是父類的hashcode,每個對象各不相同(hashset的實現暫時先不談)
重寫hashcode
class Point { private int x; private int y; public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } @Override public boolean equals(Object obj) { if (this == obj)//ref相等 { return true; } if (obj == null || this.getClass() != obj.getClass()) { return false; } Point that = (Point) obj; return x == that.x && y == that.y;//對比值 } @Override public int hashCode() { return Objects.hash(x, y); } }
再次運行
a.equals(b) is true points.contains(b) is true
同樣重寫hashcode後下麵的代碼也能輸出正常的值0000
HashMap<Point, String> map = new HashMap<>(); map.put(a, "00000"); log.info(map.get(b));
如果不重新,則會輸出null