java - 如何逐点获取地图中的值?
问题描述
我有一point
堂课:
class Point
{
public int x;
public int y;
public Point(int x,int y)
{
this.x=x;
this.y=y;
}
}
我有一个map
存储值:
Map<Point,Integer> map = new HashMap<Point,Integer>();
map.put(new point(1,1)) = 10;
我想map
通过一个明确的点来获取值:
map.get(new point(1,1));
但它返回null
。这可能是因为他们的参考不同。我想知道如何修复它,而不是使用二维数组。
解决方案
当使用 Map 类之类的结构时,您应该实现 equals 和 hashCode 方法,因此当 Map 的 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);
}
}
推荐阅读
- python-3.x - pandas 内部如何执行滚动窗口?
- python - 使用 sklearn 从数据集中删除冗余
- javascript - 从通过 Ajax XHR Get 请求获取的 HTML 页面解析和访问 Dom 元素
- spring-boot - Spring 事务管理 - AspectJ - 编译时加载 - 示例
- ruby-on-rails - Rails:如何按连接表中的列分组
- powershell - 从 txt 禁用多个计算机帐户
- python - 在 save() 上复制 Imagefield - django
- ruby-on-rails - Ruby数组到带有两行的html表
- android - 将图像转换为 Base64 字符串 Android
- jquery - 使用 jQuery 将图像转换为 base64 - 我已经在 src="images/YouthMember.jpg" 加载了一个图像,需要将其转换为 base64