In Java 9 List
,Set
and Map
interface we have of
method which support varargs (static <E> List<E> of(E... elements)
), so what's the purpose of having separate methods having arguments one to ten.
static <E> List<E> of(E e1) //Returns an unmodifiable list containing one elements.
static <E> List<E> of(E e1, E e2) //Returns an unmodifiable list containing two elements.
static <E> List<E> of(E e1, E e2, E e3) //Returns an unmodifiable list containing three elements.
static <E> List<E> of(E e1, E e2, E e3, E e4) //Returns an unmodifiable list containing four elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5) //Returns an unmodifiable list containing five elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6) //Returns an unmodifiable list containing six elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7) //Returns an unmodifiable list containing seven elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8) //Returns an unmodifiable list containing eight elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9) //Returns an unmodifiable list containing nine elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) //Returns an unmodifiable list containing ten elements.
To create a list with more than three element's the List.of
method which support varargs , is calling new ImmutableCollections.ListN<>(elements);
. This is also same for List<E> of(E e1, E e2, E e3)
to List<E> of(E e1, E e2, E e3,....E e10)
.
Implementation of List.of
method which support varargs
static <E> List<E> of(E... elements) {
switch (elements.length) { // implicit null check of elements
case 0:
@SuppressWarnings("unchecked")
var list = (List<E>) ImmutableCollections.EMPTY_LIST;
return list;
case 1:
return new ImmutableCollections.List12<>(elements[0]);
case 2:
return new ImmutableCollections.List12<>(elements[0], elements[1]);
default:
return new ImmutableCollections.ListN<>(elements);
}
}
Implementation of List.of
method which support 10 elements.
static <E> List<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E e7, E e8, E e9, E e10) {
return new ImmutableCollections.ListN<>(e1, e2, e3, e4, e5,
e6, e7, e8, e9, e10);
}