Java中的HashMap如何使用equals()和hashCode()来查找对象?

时间:2018-06-05 07:07:59

标签: java hashmap equals

我已经定义了一个Point类,如下所示,覆盖了equals()hashCode()。我期待在main()方法," Key Found"将被打印,但事实并非如此。

据我了解,Java使用equals()hashCode()HashMap中添加或查找对象。我不确定我在这里做错了什么。

import java.util.*;

public class Point {
  int row = 0;
  int col = 0;

  public Point(int row, int col) {
    this.row = row;
    this.col = col;
  }

  public String toString() {
    return String.format("[%d, %d]", row, col);
  }

  public boolean equals(Point p) {
    return (this.row == p.row && this.col == p.col);
  }

  public int hashCode() {
    return 31 * this.row + this.col;
  }

  public static void main(String[] args) {
    HashMap<Point, Integer> memo = new HashMap<>();
    Point x = new Point(1, 2);
    Point y = new Point(1, 2);
    memo.put(x, 1);

    if (x.equals(y))
      System.out.println("x and y are equal");

    System.out.println("Hashcode x= " + x.hashCode() + " Hashcode y= " + 
                       y.hashCode());

    if (memo.containsKey(y)) {
      System.out.println("Key found");
    }
  }
}

output
x and y are equal
Hashcode x= 33 Hashcode y= 33

1 个答案:

答案 0 :(得分:7)

问题在于您实际上并未覆盖equals()方法。 equals() method that you are trying to overrideObject作为参数,而不是Point对象。因此,您实施的equals()方法实际上并未被调用。