I was just looking at Guava’s ImmutableList and I noticed that the of() method was overloaded 12 times.
It looks to me that all they needed was:
static <E> ImmutableList<E> of();
static <E> ImmutableList<E> of(E element); // not even necessary
static <E> ImmutableList<E> of(E... elements);
What’s the reason for having so many similar variations?
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:
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@SafeVarargscould be used and would not give warnings with generic arguments.