-1

Why are there multiple of static factory methods in java util.List interface depending on the number of arguments, from 1 to 10? Was it not possible to have just one method that will take an array as input parameter?

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
aarnaut
  • 507
  • 6
  • 17
  • Would you always want to create an array to initialize? If you already have an array you can use Arrays.asList – CannedMoose Apr 14 '18 at 08:32
  • @CannedMoose I would expect to just have an interface method `of(args...)` since these static factory anyway call `ImmutableCollection` constructor which takes an `args..` input unless it has 2 or less parameters. – aarnaut Apr 14 '18 at 08:36

2 Answers2

3

they implemented 1 to 10 and >10, cause 1 to 10 are commonly used and offer a great deal of performance boost than using variable length of args input to the function e.g args...

shahaf
  • 4,750
  • 2
  • 29
  • 32
  • There are 4 different implementations of `ImmutableCollections.List` depending on the number of arguments (0, 1, 2, n). Why not just have that one `of(args..)` method that will create different list based on the number of parameters? All those other static factory methods that take more than 2 parameters will use ListN. Correct? – aarnaut Apr 14 '18 at 08:38
  • I see your point now. Thanks you. – aarnaut Apr 14 '18 at 08:45
2

I have found an answer in an article of Java World which seems pretty logical when you think about it.

In each method list, the first method creates an empty unmodifiable collection. The next 10 methods create unmodifiable collections with up to 10 elements. Despite their API clutter, these methods avoid the array allocation, initialization, and garbage collection overhead incurred by the final varargs method, which supports arbitrary-sized collections.

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89