Reputation: 6622
as jvm manages string pool for String from which it looks up for any new String assignment, similarly, can we develop a pool of any other object or primitives?
Upvotes: 5
Views: 589
Reputation: 726519
The interning pool for Java String constants is something known to the Java compiler, so you cannot mimic the exact behavior by yourself.
The pool itself, however, is nothing more than a hash map. If your object has a suitable identifier, you can certainly roll a pool for your own objects: simply create a static method that takes a key, looks it up in a static hash map, and builds a new object only if it has not been pooled yet. Note, however, that in orde for this simple scheme to work, it is essential for your object to be immutable.
Upvotes: 4
Reputation: 136002
String pool is not the only pool / cache in Java, Integer and other wrapper classes use cache, you can take a look at the Integer source code as an example
public static Integer valueOf(int i) {
assert IntegerCache.high >= 127;
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}
you can also take a look at http://commons.apache.org/proper/commons-pool//
Upvotes: 3