How would I write a generic InternPool
in Java? Does it need a Internable
interface?
String
in Java has interning cap
Just a quick caveat:
It has not been explicitly mentioned above, but it should be obvious that the objects being interned must be of an immutable type.
On a second note: You don't need to use another weak reference to the object as the value in the map, a reference to a static would suffice if you just rely on the map's keyset for the data. For example, declare:
WeakHashMap
And insert pairs as:
pool.put (object, Boolean.TRUE);
Which is a minor saving of a WeakReference instance (if you can't reuse the one used for the key).
...or create a WeakSet class, as @PeterVerhas has done with his WeakPool.