如何让相同变量值的Position对象可作为Map键或复用引用?
解决方案:让Position类可作为Map键或返回相同引用
方案一:正确实现equals()和hashCode()方法
这是解决Map键匹配问题的核心方案。HashMap等哈希Map通过hashCode()确定键的存储位置,再用equals()验证匹配关系。只要基于x、y、layer三个字段实现这两个方法,就能让相同坐标的不同Position对象被视为同一个键。
代码示例:
import java.util.Objects; public final class Position { private final int x, y, layer; public Position(int x, int y, int layer) { this.x = x; this.y = y; this.layer = layer; } public int getX() { return x; } public int getY() { return y; } public int getLayer() { return layer; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Position position = (Position) o; return x == position.x && y == position.y && layer == position.layer; } @Override public int hashCode() { return Objects.hash(x, y, layer); } }
实现后,直接用新创建的相同坐标Position对象作为键,就能访问positionMap中对应的值,无需遍历所有键。
方案二:享元模式——返回相同值的同一引用
如果希望所有值相同的Position对象共享同一个实例,可以用享元模式,通过静态工厂方法复用实例,从根源上保证相同值的对象引用一致。
代码示例:
import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; public final class Position { private final int x, y, layer; private static final Map<Position, Position> INSTANCE_CACHE = new ConcurrentHashMap<>(); // 构造方法私有化,强制通过工厂方法创建实例 private Position(int x, int y, int layer) { this.x = x; this.y = y; this.layer = layer; } // 工厂方法:复用已有实例,不存在则创建 public static Position of(int x, int y, int layer) { Position key = new Position(x, y, layer); // 依赖equals和hashCode的正确实现来匹配缓存 return INSTANCE_CACHE.computeIfAbsent(key, k -> k); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Position position = (Position) o; return x == position.x && y == position.y && layer == position.layer; } @Override public int hashCode() { return Objects.hash(x, y, layer); } }
调用Position.of(x,y,layer)时,会优先返回缓存中的实例,确保相同坐标的对象引用完全一致,作为Map键时不会有任何匹配问题,还能减少内存占用。
补充说明
- 方案一已能满足Map键的基本需求,是通用做法;方案二更适合需要大量复用相同值对象的场景。
- 若使用
TreeMap,无需重写hashCode(),但需要让Position实现Comparable<Position>接口,或创建TreeMap时传入自定义Comparator,确保相同值的对象被视为相等键。
内容的提问来源于stack exchange,提问作者Joseph Wong
相关产品推荐
相关产品推荐

