It can be "reused" because you can use the same object in several places, and everything will be fine. But this will not happen, automatically. The JVM itself manages the reuse of Integer objects for the range -128 - 127
Java Integer Caching
"static" strings (including literals) are similarly managed by the JVM. The closest thing you could to automatic reuse here would be to make the constructor private and create a factory method:
Point.create(int x, int y)
And the implementation has a cache of objects that you want to reuse (for example, whole elements effectively cache -128 to 127). But you have to do this work yourself.
Edit:
Basically you:
private static final Map<Pair<Integer, Integer>, Point> cache = new HashMap<>(); public Point create(int x, int y) { Pair<Integer, Integer> 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; }
Edit: Also, add hashCode () and equals () to the Point class and just use a HashSet. It would be easier.
source share