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

Tan*_*anM 4 java equals hashmap

我已经定义了一个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
Run Code Online (Sandbox Code Playgroud)

ent*_*erd 7

问题是你实际上没有覆盖该equals()方法.在equals()您试图重写方法需要在Object作为参数,而不是一个Point对象.因此,equals()实际上并未调用您实现的方法.