Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List `of` method is quite confusing

Tags:

java

list

When I look at java documents at List of method

It is quite overloaded, with all the number of elements from 1 to 10...

And It says:

Returns an unmodifiable list containing five elements.

See Unmodifiable Lists for details.

Type Parameters: E - the List's element type Parameters: e1 - the first element e2 - the second element e3 - the third element e4 - the fourth element e5 - the fifth element

I just don't understand this at all, and could find a way to even use this?

like image 666
jxie0755 Avatar asked May 31 '26 17:05

jxie0755


1 Answers

The List.of() methods are convenient static helpers to create a fixed-size list in one call (instead of creating an empty list and then calling add a few times). It so happens that the list returned by this call is unmodifiable (no elements may be added or removed).

As an example, compare:

ArrayList<String> supportedLanguages = new ArrayList<>();
supportedLanguages.add("en-us");
supportedLanguages.add("en-gb");
supportedLanguages.add("de");

to:

List<String> supportedLanguages = List.of("en-us", "en-gb", "de");

There happen to be eleven such overloads, taking from zero to ten elements (List.of() turns to an empty unmodifiable list), and larger cases are handled using a vararg overload with signature @SafeVarargs static <E> List<E> of​(E... elements).

like image 152
nanofarad Avatar answered Jun 03 '26 10:06

nanofarad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!