Is there any pool system like String pool for List.of()

Viewed 64

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?

1 Answers

"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);
    }
}
Related