我正在尝试使用 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)));
}
}
Run Code Online (Sandbox Code Playgroud)
我期望输出是:
A
Run Code Online (Sandbox Code Playgroud)
但是,输出是:
null …Run Code Online (Sandbox Code Playgroud)