【发布时间】:2017-11-24 22:34:55
【问题描述】:
我正在尝试使用 HashMap 实现一个稀疏网格,但似乎覆盖 hashCode() 并不能完全按照我的预期工作。我将我的问题归结为以下代码:
public class Main {
private static class Coord {
int x, y;
public Coord(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public int hashCode() {
// See https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function
return (((x + y) * (x + y + 1)) / 2) + y;
}
}
public static void main(String[] args) {
HashMap<Coord, String> grid = new HashMap<Coord, String>();
grid.put(new Coord(0, 0), "A");
System.out.println(grid.get(new Coord(0, 0)));
}
}
我希望输出是:
A
但是,输出是:
null
两个“new Coord(0, 0)”实例都应该返回相同的 hashCode(),但它似乎没有按我的预期工作。为什么它没有按我的预期工作?
【问题讨论】:
-
你还需要覆盖equals
-
HashMap需要hashCode和equals来做你想做的事情。
标签: java hashmap grid sparse-matrix hashcode