3

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?

jxie0755
  • 1,682
  • 1
  • 16
  • 35
  • When I have a question about Java I search " -site:oracle.com" because their docs are second worse to Github... – Stepan Mar 09 '19 at 04:26
  • @Stepan What do u mean? – jxie0755 Mar 09 '19 at 04:31
  • Java docs are poorly written. There are no examples, just a list of flags. Github went a step down: used vague names for the flags and spits errors, but doesn't suggest solutions. When I search info about Java methods I tell search engine to hide/exclude oracle docs from the search results. Reading Oracle docs is usually a waste of the time. – Stepan Mar 09 '19 at 14:21
  • So where do you usually go to check java methods? checking on people’s blogs? – jxie0755 Mar 09 '19 at 14:28
  • see my "-site" in the query. first reesults are usually good. ttps://www.google.com/search?q=java+list+of+method+-site%3Aoracle.com&oq=java+list+of+method+-site%3Aoracle.com – Stepan Mar 09 '19 at 14:43

3 Answers3

6

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).

nanofarad
  • 40,330
  • 4
  • 86
  • 117
  • I see. But why is it useful if I have: `List intList = new ArrayList<>(Arrays.asList(1,2,1,3,1,4));` – jxie0755 Mar 09 '19 at 03:37
  • 1
    @Code_Control_jxie0755 because it is unmodifiable - you can't add or delete new elements. In your example, you can still add or delete elements. – vs97 Mar 09 '19 at 03:39
  • 1
    @Code_Control_jxie0755 I can't speak to why, since it's a decision made by the developers of the Java SE API itself. I've never thought to use that version. Before `List.of` was a thing I was working at a company whose internal libraries had an `ImmutableList.of(...)` in the same structure (overloads for 0-10 elements and varargs for more). From a *cursory* inspection I don't see any massive differences between `Arrays.asList` and `List.of`, except for the fact that non-vararg overloads don't require the construction (and ultimately the gabage collection overhead) for a short-lived array) – nanofarad Mar 09 '19 at 03:39
  • @vs97 so That is even better? I guess? – jxie0755 Mar 09 '19 at 03:39
  • @Code_Control_jxie0755 depends entirely on your use case. – vs97 Mar 09 '19 at 03:39
  • 1
    @Code_Control_jxie0755 You should strive for *readability* of code above anything else. `List.of()` is very readable and almost rolls off the tongue. In my answer, I can almost effortlessly translate the second example to prose as "a list consisting of en-us, en-gb, and de". – nanofarad Mar 09 '19 at 03:41
3

Since jdk-9 there are 10 overloaded methods and one vararg method List.of() to create unmodifiable list, which mean you cannot modify the list by removing or adding elements to it.

static <E> List<E> of()    //Returns an unmodifiable list containing zero elements. See Unmodifiable Lists for details.
static <E> List<E> of​(E e1)   //Returns an unmodifiable list containing one element. See Unmodifiable Lists for details.
static <E> List<E> of​(E e1, E e2)   //Returns an unmodifiable list containing two elements. See Unmodifiable Lists for details.
static <E> List<E> of​(E e1, E e2, E e3)   //Returns an unmodifiable list containing three elements. See Unmodifiable Lists for details.
.
.
.

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. See Unmodifiable Lists for details.

@SafeVarargs static <E> List<E> of​(E... elements)   //Returns an unmodifiable list containing an arbitrary number of elements. See Unmodifiable Lists for details.

And E is type parameter to just create list of Generic type

List<Integer> list = List.of(1,2,3);  // unmodifiable list with 3 integer elements
List<String> list = List.of("hello","world");   //// unmodifiable list with 2 string elements

Suppose if you need a list that can be accessible over application level and no one can modify the list, In that purpose you can choose them.

Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
2

The three interfaces List, Set, and Map all gained the new overloaded .of methods.

List< Integer > luckyNumbers = List.of( 7 , 11 , 42 ) ;

Set< DayOfWeek > weekend = Set.of( DayOfWeek.SATURDAY , DayOfWeek.SUNDAY ) ;

Map< DayOfWeek , Employee > dutyRoster = 
    Map.of(
        DayOfWeek.MONDAY , alice ,
        DayOfWeek.TUESDAY , bob ,
        DayOfWeek.WEDNESDAY , alice ,
        DayOfWeek.THURSDAY , carol , 
        DayOfWeek.FRIDAY , carol
    )
;

Convenience

Being able to declare and populate a List, Set, or Map in a single line of code is quite convenient. Short, elegant, clearly expresses the programmer’s intention.

Not modifiable

Frequently, such short collections of objects are intended to be read-only. Meaning, the programmer using the collection cannot add, delete, or replace any of the collected objects.

Be aware that the content inside the collected objects may or may not be mutable. That is outside the scope of the collection’s duties.

The Collections utility class provided ways to make a collection unmodifiable, but you had to go out of your way to make use of this feature. And doing so meant more lines of code. The new .of methods are simpler.

Optimization

Note that you get back an object of the interface rather than a class. So for example, List rather than ArrayList, Set rather than HashSet, Map rather than HashMap. You have no idea what concrete class is in use by the returned object. Nor do you care.

This means the Java team is free to optimize the concrete implementation, changing the code from one release to another. They may even choose at runtime to use different implementations depending on the count or type of your objects being collected.

For example, if your collected objects are of an enum type, then the highly-optimized EnumSet could be used behind the scene to fulfill your request for a Set.of. Likewise, EnumMap for Map.of. See the Set and Map code at the top of this Answers as examples of enum objects being collected and therefore eligible for this optimization.

This freedom to optimize has been discussed by Brian Goetz and others.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154