它可以“重复使用”,因为你可以在多个地方使用同一个对象,这样就可以了.但它不会自动发生. JVM本身管理重用Integer对象的范围为-128 – 127
“intern”ed字符串(包括文字)类似地由JVM管理.您可以在此处使用最接近自动重用的方法是将构造函数设为私有,并创建工厂方法:
Point.create(int x, int y)
并且让实现维护你想要重用的对象的缓存(比如整数有效地缓存-128到127)但是你必须自己做这项工作.
编辑:
你基本上有:
private static final Map, Point> cache = new HashMap<>();
public Point create(int x, int y) {
Pair key = Pair.of(x, y);
if (cache.containsKey(key)) {
return cache.get(key);
}
Point p = new Point(x, y);
cache.put(key, p);
return p;
}
编辑:或者,将hashCode()和equals()添加到Point类,并使用HashSet.会更简单.