1

As you can see here in documentation that there are 11 methods named of in Set:

static <E> Set<E> of​()
static <E> Set<E> of(E e1)
static <E> Set<E> of(E e1, E e2)
//similar 8 methods like above till e10

Now coming to the 12th var-args method:

static <E> Set<E> of(E... elements)

The method in second snippet essentially does the same as those methods in the first snippet. My question is, why did Java developers included the 11 arbitrary methods(first snippet) in Set interface? Do we really need those methods when we have a var-args method?

And which method will be invoked if I pass only one argument to of?

static <E> Set<E> of(E e1) or static <E> Set<E> of(E... elements).

  • 1
    Most likely for performance reasons - to use varargs, an array needs to be created which is passed to the method; without varargs, creating this array is avoided. Which method will be invoked if you pass only one argument: Obviously, the version that takes one argument! – Jesper Dec 20 '17 at 13:41
  • 3
    [Now you may ask, what is the point of having 11 extra methods if there’s a var-args version which can work for any number of elements. The answer to that is performance. Every var-args method call implicitly creates an array. Having the overloaded methods avoid unnecessary object creation and the garbage collection overhead thereof.](http://www.baeldung.com/java-9-collections-factory-methods) – daniu Dec 20 '17 at 13:41

1 Answers1

4

If you pass a single argument, static <E> Set<E> of(E e1) will be executed, since methods with varargs have a lower priority during method overloading resolution (i.e. they are only considered by the compiler if no methods without varargs are applicable).

The 11 of methods were created for performance reasons. They are more efficient than the varargs method, since the varargs method requires instantiation of an array.

Eran
  • 387,369
  • 54
  • 702
  • 768
  • 2
    nitpick, only 2 of them at the moment are using a separate implementation, others still delegate to `var-args` – Eugene Dec 20 '17 at 14:50