Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - tell if a String is interned?

Tags:

java

string

So the question here is pretty simple: is there a way to tell if a String in Java is interned? My guess is no, but I'm wondering if anyone knows better.

like image 924
Masterofpsi Avatar asked Feb 03 '11 08:02

Masterofpsi


2 Answers

The only way you can find out if a String is interned is to call intern() and check if it returns itself:

boolean hasBeenInternedBefore = myString.intern() == myString;

This obviously has the drawback of interning the String when it wasn't interned before.

Going partially off-topic, there's a way to do "custom" interning with an explicit pool using the Interner interface of Guava (using the implementations exposed by the Interners class). This has the advantage of being able to let the Interner itself (and thuse the pool) being garbage collected when it's no longer referenced.

like image 167
Joachim Sauer Avatar answered Oct 21 '22 22:10

Joachim Sauer


There is a way to check if the particular String object was already interned, but it inserts the contents into the string pool if those contents weren't already interned. Create a new String object with the same contents, intern that, and compare to your original object:

new String(s).intern() == s

This works because of the fact that new String(s) != s. Consider each possible situation:

  1. s is interned in the string pool. new String(s) has the same contents as s, so intern() called on it will return s. The expression's result is true.
  2. s is not interned in the string pool, but another equal String object is—let's call it s2. intern() will return s2, so the expression's result is false.
  3. s is not interned in the string pool, and neither is any String equal to it. In this case, new String(s) will be interned into the string pool, which unfortunately modifies the string pool. Because this is not the same String object as s, the expression's result is false.

Thus the above expression will correctly test if s is interned in the string pool or not. The following test demonstrates this:

public static void main(String[] args) {
    String interned = new String(new char[] { 'i', 'n', 't' }).intern();
    String notInterned = new String(new char[] { 'n', 'o', 't' });
    System.out.println("Case 1: " + wasInterned(interned));
    System.out.println("Case 2: " + wasInterned(new String(interned)));
    System.out.println("Case 3: " + wasInterned(notInterned));
}

public static boolean wasInterned(String s) {
    return new String(s).intern() == s;
}

When run, the output is:

 Case 1: true
 Case 2: false
 Case 3: false
like image 35
Dan Getz Avatar answered Oct 21 '22 20:10

Dan Getz