2

Suppose I have the following method:

private boolean isExist(String key) {
   return List.of("a", "b", "c", "d", "e").contains(key);
}

Does this create N number of List.of("a", "b", "c", "d", "e") objects for N method executions? Or is there any kind of mechanism like string pool internally?

Sean Mickey
  • 7,618
  • 2
  • 32
  • 58
A M S Rejuan
  • 447
  • 6
  • 12
  • Not sure what exactly you want, but String objects do have pool and they are usually handled by JVM, you can read a bit more here: https://stackoverflow.com/questions/10578984/what-is-java-string-interning EDIT: also your code snippet if invalid. – whatamidoingwithmylife Apr 03 '20 at 10:23
  • 2
    No, there is no pool for lists. – Andreas Apr 03 '20 at 10:25
  • 1
    *FYI:* If you want to call `contains()` you should use `Set.of()`, not `List.of()`, for better lookup performance. – Andreas Apr 03 '20 at 10:26
  • 2
    Maybe this list should be `final static`if you are worrying about memory usage – jhamon Apr 03 '20 at 10:27
  • @jhamon Thanks. Yes, we can use `final static`. I am interested to know the JVM behavior for this `List.of()`. – A M S Rejuan Apr 03 '20 at 10:30

1 Answers1

2

"a", "b", "c", "d", "e" will be moved to the string pool unless they are already there. Next time you are accessing any of them (for example, "a"), no objects will be created, just pulled from the pool.

What you are asking is irrelevant to the pool, though. It largely depends on the implementation of List being returned. It could always return a new list (which is highly likely) or extract it from an internal cache (which is improbable since it's not effective for data structures of arbitrary size - imagine how expensive a lookup in that kind of cache would be).

Java 9's implementation looks like

static <E> List<E> of(E e1) {
    return new List12(e1);
}

static <E> List<E> of(E e1, E e2) {
    return new List12(e1, e2);
}

static <E> List<E> of(E e1, E e2, E e3) {
    return new ListN(new Object[]{e1, e2, e3});
}

with some nice micro-optimisations

@SafeVarargs
static <E> List<E> of(E... elements) {
    switch(elements.length) {
    case 0:
        return ImmutableCollections.emptyList();
    case 1:
        return new List12(elements[0]);
    case 2:
        return new List12(elements[0], elements[1]);
    default:
        return new ListN(elements);
    }
}
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142