我有一point堂课:
class Point
{
public int x;
public int y;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个map存储值:
Map<Point,Integer> map = new HashMap<Point,Integer>();
map.put(new point(1,1)) = 10;
Run Code Online (Sandbox Code Playgroud)
我想map通过一个明确的点来获取值:
map.get(new point(1,1));
Run Code Online (Sandbox Code Playgroud)
但它返回null。这可能是因为他们的参考不同。我想知道如何修复它,而不是使用二维数组。
当使用像 Map 类这样的结构时,你应该实现 equals 和 hashCode 方法,这样当 Map get 的 get 方法被调用时,这些方法将分别调用
像这样:
class Point {
public int x;
public int y;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Point point = (Point) o;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
67 次 |
| 最近记录: |