簡體   English   中英

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

[英]How does HashMap in Java use equals() and hashCode() to find objects?

我已經定義了一個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

問題是你實際上沒有覆蓋equals()方法。 您嘗試覆蓋equals()方法Object作為參數,而不是Point對象。 因此,實際上不會調用您實現的equals()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM