Why do I see this scheme listing many methods for arguments 1,2,3, etc., followed by a general list of arguments of arbitrary size?

ImmutableList is one example of what I'm talking about. There are a number of methods that take a fixed number of arguments, followed by a common signature of all signatures

  public static <E> ImmutableList<E> of(E element) {
    return new RegularImmutableList<E>(copyIntoArray(element));
  }

  public static <E> ImmutableList<E> of(E e1, E e2) {
    return new RegularImmutableList<E>(copyIntoArray(e1, e2));
  }

  public static <E> ImmutableList<E> of(E e1, E e2, E e3) {
    return new RegularImmutableList<E>(copyIntoArray(e1, e2, e3));
  }

  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4) {
    return new RegularImmutableList<E>(copyIntoArray(e1, e2, e3, e4));
  }

  public static <E> ImmutableList<E> of(E e1, E e2, E e3, E e4, E e5) {
    return new RegularImmutableList<E>(copyIntoArray(e1, e2, e3, e4, e5));
  }

  public static <E> ImmutableList<E> of(E... elements) {
    return (elements.length == 0)
        ? ImmutableList.<E>of()
        : new RegularImmutableList<E>(copyIntoArray(elements));
  }

(Comments removed for brevity).

Why not include only the final catch of everything (elements E ...). I guess the answer is something like “optimization,” but I don’t quite understand why. Is checking and branching for .length == 0 elements really considered expensive?

Why dwell on only 5 arguments, why not 10 or 50?

- Java -, ?

+3

All Articles