How would I write a generic InternPool
in Java? Does it need a Internable
interface?
String
in Java has interning cap
I would separate the solution into two classes to have cleaner code and also this way getting rid of loop:
public class WeakPool {
private final WeakHashMap> pool = new WeakHashMap>();
public T get(T object) {
final T res;
WeakReference ref = pool.get(object);
if (ref != null) {
res = ref.get();
} else {
res = null;
}
return res;
}
public void put(T object) {
pool.put(object, new WeakReference(object));
}
}
and the interning class using the weak pool is very simple:
public class InternPool {
private final WeakPool pool = new WeakPool();
public synchronized T intern(T object) {
T res = pool.get(object);
if (res == null) {
pool.put(object);
res = object;
}
return res;
}
}