Why does Guava’s ImmutableList have so many overloaded of() methods?

Varargs and generics do not play nicely together. Varargs methods can cause a warning with generic arguments, and the overloads prevent that warning except in the rare case that you want to add more than 11 items to the immutable list using of().

The comments in the source say:

These go up to eleven. After that, you just get the varargs form, and whatever warnings might come along with it. 🙁

Note that Java 7’s @SafeVarargs annotation was added specifically to eliminate the need for this sort of thing. A single of(E...) method annotated with @SafeVarargs could be used and would not give warnings with generic arguments.

Leave a Comment