This cannot be related to performance, in fact: all methods are delegated to the same creation method that the array expects anyway.
I guess this is due to warnings. Consider the following minimal snippet:
import java.util.List; class ImmutableSet<T> { } public class ParametersTest { public static void main(String[] args) { List<String> list0 = null; List<String> list1 = null; of(list0, list1); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2) { return create(e1, e2); } public static <E> ImmutableSet<E> of(E... elements) { return create(elements); } private static <E> ImmutableSet<E> create(E... elements) { return null; } }
The call of of in the main method is in order: it corresponds to the 2-args version of the of method. Now comment out the 2-args version of the of method. Then the call is still fine, but will directly invoke the varags version. This will create a shared array and trigger a warning. (This warning is suppressed in version 2-args, obviously).
So, to summarize, I assume that this is necessary to avoid warnings for library clients who want to call the of method with several objects of a generic type.
Fortunately, such things will no longer be needed in the future thanks to http://docs.oracle.com/javase/7/docs/api/java/lang/SafeVarargs.html
Marco13
source share