小编Tan*_*anM的帖子

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

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

java equals hashmap

4
推荐指数
1
解决办法
118
查看次数

标签 统计

equals ×1

hashmap ×1

java ×1