3
List.of()
List.of(E e1)
List.of(E e1, E e2)
List.of(E e1, E e2, E e3)
List.of(E e1, E e2, E e3, E e4)
List.of(E e1, E e2, E e3, E e4, E e5)
List.of(E e1, E e2, E e3, E e4, E e5, E e6)
List.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7)
List.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8)
List.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9)
List.of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10)
List.of(E... elements)

Isn't this crazy? Why not just:

List.of(E... elements)

(Source: https://github.com/netroby/jdk9-dev/blob/master/jdk/src/java.base/share/classes/java/util/List.java)

The Map interface looks more wasteful with the longest overloaded version having 20 parameters:

Map.of(K k1, V v1, K k2, V v2, K k3, V v3, K k4, V v4, K k5, V v5, K k6, V v6, K k7, V v7, K k8, V v8, K k9, V v9, K k10, V v10)
MGhostSoft
  • 528
  • 4
  • 13
  • 7
    The variadic form creates an array instance if you invoke it. The explicit overloads avoid unnecessary object creation. – Andy Turner Aug 25 '16 at 22:07
  • 2
    Further to @AndyTurner, the `Map.of` method needs to have an **even** number of arguments - having explicit methods allows this to be verified at compile time. – Boris the Spider Aug 25 '16 at 22:09
  • 1
    maybe they had time to waist :D. I think it's to enhance performance by reducing object creation, and access time. – whyn0t Aug 25 '16 at 22:15
  • 1
    @BoristheSpider and, they have to be of alternating types `K` and `V`; you couldn't have such a variadic method unless `K` and `V` were equal. – Andy Turner Aug 25 '16 at 22:48
  • @AndyTurner very good point. – Boris the Spider Aug 25 '16 at 22:49
  • "_maybe they had time to waist_" - are you calling them fat @whyn0t? – Boris the Spider Aug 25 '16 at 22:50
  • @AndyTurner Why does Guava's Lists.newArrayList has only two versions, one with no arg and the other is variadic? Or the question should be: why does ImmutableList matter only? – MGhostSoft Sep 02 '16 at 00:42
  • 1
    @MGhostSoft interesting question, I don't know! My assumption would be that it simply wasn't a common enough case in Google's code to need to address in the same way. Let's be honest: having to explicitly expand variadic parameters *is ugly*, so it's something you are only going to want to do where it carries its weight; perhaps the Java libraries team found it didn't in the case of `Lists.newArrayList`. – Andy Turner Sep 02 '16 at 06:50

0 Answers0