Java List `of` method is quite confusingWhen do you use varargs in Java?Is Java “pass-by-reference” or “pass-by-value”?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How to make a flat list out of list of lists?How do I concatenate two lists in Python?How to clone or copy a list?Creating a memory leak with Java

Why doesn't Newton's third law mean a person bounces back to where they started when they hit the ground?

How do I create uniquely male characters?

How to write a macro that is braces sensitive?

How did the USSR manage to innovate in an environment characterized by government censorship and high bureaucracy?

Do VLANs within a subnet need to have their own subnet for router on a stick?

What are these boxed doors outside store fronts in New York?

Can an x86 CPU running in real mode be considered to be basically an 8086 CPU?

GPS Rollover on Android Smartphones

Shell script not opening as desktop application

How to test if a transaction is standard without spending real money?

The magic money tree problem

Is it unprofessional to ask if a job posting on GlassDoor is real?

Mathematical cryptic clues

Why has Russell's definition of numbers using equivalence classes been finally abandonned? ( If it has actually been abandonned).

Animated Series: Alien black spider robot crashes on Earth

Basic combinations logic doubt in probability

Do any Labour MPs support no-deal?

Why did the Germans forbid the possession of pet pigeons in Rostov-on-Don in 1941?

Is there really no realistic way for a skeleton monster to move around without magic?

Magento 2: Admin panel 3 level menu structure not working

Explain the parameters before and after @ in the treminal

Is it possible to do 50 km distance without any previous training?

Show that if two triangles built on parallel lines, with equal bases have the same perimeter only if they are congruent.

How old can references or sources in a thesis be?



Java List `of` method is quite confusing


When do you use varargs in Java?Is Java “pass-by-reference” or “pass-by-value”?How do I check if a list is empty?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow do I read / convert an InputStream into a String in Java?How do I generate random integers within a specific range in Java?How to make a flat list out of list of lists?How do I concatenate two lists in Python?How to clone or copy a list?Creating a memory leak with Java






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








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?










share|improve this question
























  • When I have a question about Java I search "<Java method> -site:oracle.com" because their docs are second worse to Github...

    – Stepan
    Mar 9 at 4:26












  • @Stepan What do u mean?

    – Code_Control_jxie0755
    Mar 9 at 4: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 9 at 14:21












  • So where do you usually go to check java methods? checking on people’s blogs?

    – Code_Control_jxie0755
    Mar 9 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 9 at 14:43


















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?










share|improve this question
























  • When I have a question about Java I search "<Java method> -site:oracle.com" because their docs are second worse to Github...

    – Stepan
    Mar 9 at 4:26












  • @Stepan What do u mean?

    – Code_Control_jxie0755
    Mar 9 at 4: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 9 at 14:21












  • So where do you usually go to check java methods? checking on people’s blogs?

    – Code_Control_jxie0755
    Mar 9 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 9 at 14:43














3












3








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?










share|improve this question
















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?







java list






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 9 at 3:34







Code_Control_jxie0755

















asked Mar 9 at 3:28









Code_Control_jxie0755Code_Control_jxie0755

545416




545416












  • When I have a question about Java I search "<Java method> -site:oracle.com" because their docs are second worse to Github...

    – Stepan
    Mar 9 at 4:26












  • @Stepan What do u mean?

    – Code_Control_jxie0755
    Mar 9 at 4: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 9 at 14:21












  • So where do you usually go to check java methods? checking on people’s blogs?

    – Code_Control_jxie0755
    Mar 9 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 9 at 14:43


















  • When I have a question about Java I search "<Java method> -site:oracle.com" because their docs are second worse to Github...

    – Stepan
    Mar 9 at 4:26












  • @Stepan What do u mean?

    – Code_Control_jxie0755
    Mar 9 at 4: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 9 at 14:21












  • So where do you usually go to check java methods? checking on people’s blogs?

    – Code_Control_jxie0755
    Mar 9 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 9 at 14:43

















When I have a question about Java I search "<Java method> -site:oracle.com" because their docs are second worse to Github...

– Stepan
Mar 9 at 4:26






When I have a question about Java I search "<Java method> -site:oracle.com" because their docs are second worse to Github...

– Stepan
Mar 9 at 4:26














@Stepan What do u mean?

– Code_Control_jxie0755
Mar 9 at 4:31





@Stepan What do u mean?

– Code_Control_jxie0755
Mar 9 at 4: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 9 at 14:21






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 9 at 14:21














So where do you usually go to check java methods? checking on people’s blogs?

– Code_Control_jxie0755
Mar 9 at 14:28





So where do you usually go to check java methods? checking on people’s blogs?

– Code_Control_jxie0755
Mar 9 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 9 at 14:43






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 9 at 14:43













3 Answers
3






active

oldest

votes


















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






share|improve this answer

























  • I see. But why is it useful if I have: List<Integer> intList = new ArrayList<>(Arrays.asList(1,2,1,3,1,4));

    – Code_Control_jxie0755
    Mar 9 at 3: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 9 at 3: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)

    – Andrey Akhmetov
    Mar 9 at 3:39












  • @vs97 so That is even better? I guess?

    – Code_Control_jxie0755
    Mar 9 at 3: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".

    – Andrey Akhmetov
    Mar 9 at 3: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.






share|improve this answer

























  • So this looks like a tuple to me, if it is in python...

    – Code_Control_jxie0755
    Mar 9 at 3:41











  • yes exactly, but i have only limited knowledge in python @Code_Control_jxie0755

    – Deadpool
    Mar 9 at 3:42


















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.






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073707%2fjava-list-of-method-is-quite-confusing%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









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






    share|improve this answer

























    • I see. But why is it useful if I have: List<Integer> intList = new ArrayList<>(Arrays.asList(1,2,1,3,1,4));

      – Code_Control_jxie0755
      Mar 9 at 3: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 9 at 3: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)

      – Andrey Akhmetov
      Mar 9 at 3:39












    • @vs97 so That is even better? I guess?

      – Code_Control_jxie0755
      Mar 9 at 3: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".

      – Andrey Akhmetov
      Mar 9 at 3:41















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






    share|improve this answer

























    • I see. But why is it useful if I have: List<Integer> intList = new ArrayList<>(Arrays.asList(1,2,1,3,1,4));

      – Code_Control_jxie0755
      Mar 9 at 3: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 9 at 3: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)

      – Andrey Akhmetov
      Mar 9 at 3:39












    • @vs97 so That is even better? I guess?

      – Code_Control_jxie0755
      Mar 9 at 3: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".

      – Andrey Akhmetov
      Mar 9 at 3:41













    6












    6








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






    share|improve this answer















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







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 9 at 3:37

























    answered Mar 9 at 3:35









    Andrey AkhmetovAndrey Akhmetov

    30.2k46290




    30.2k46290












    • I see. But why is it useful if I have: List<Integer> intList = new ArrayList<>(Arrays.asList(1,2,1,3,1,4));

      – Code_Control_jxie0755
      Mar 9 at 3: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 9 at 3: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)

      – Andrey Akhmetov
      Mar 9 at 3:39












    • @vs97 so That is even better? I guess?

      – Code_Control_jxie0755
      Mar 9 at 3: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".

      – Andrey Akhmetov
      Mar 9 at 3:41

















    • I see. But why is it useful if I have: List<Integer> intList = new ArrayList<>(Arrays.asList(1,2,1,3,1,4));

      – Code_Control_jxie0755
      Mar 9 at 3: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 9 at 3: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)

      – Andrey Akhmetov
      Mar 9 at 3:39












    • @vs97 so That is even better? I guess?

      – Code_Control_jxie0755
      Mar 9 at 3: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".

      – Andrey Akhmetov
      Mar 9 at 3:41
















    I see. But why is it useful if I have: List<Integer> intList = new ArrayList<>(Arrays.asList(1,2,1,3,1,4));

    – Code_Control_jxie0755
    Mar 9 at 3:37





    I see. But why is it useful if I have: List<Integer> intList = new ArrayList<>(Arrays.asList(1,2,1,3,1,4));

    – Code_Control_jxie0755
    Mar 9 at 3:37




    1




    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 9 at 3:39





    @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 9 at 3:39




    1




    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)

    – Andrey Akhmetov
    Mar 9 at 3:39






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

    – Andrey Akhmetov
    Mar 9 at 3:39














    @vs97 so That is even better? I guess?

    – Code_Control_jxie0755
    Mar 9 at 3:39





    @vs97 so That is even better? I guess?

    – Code_Control_jxie0755
    Mar 9 at 3:39




    1




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

    – Andrey Akhmetov
    Mar 9 at 3:41





    @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".

    – Andrey Akhmetov
    Mar 9 at 3: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.






    share|improve this answer

























    • So this looks like a tuple to me, if it is in python...

      – Code_Control_jxie0755
      Mar 9 at 3:41











    • yes exactly, but i have only limited knowledge in python @Code_Control_jxie0755

      – Deadpool
      Mar 9 at 3:42















    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.






    share|improve this answer

























    • So this looks like a tuple to me, if it is in python...

      – Code_Control_jxie0755
      Mar 9 at 3:41











    • yes exactly, but i have only limited knowledge in python @Code_Control_jxie0755

      – Deadpool
      Mar 9 at 3:42













    3












    3








    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.






    share|improve this answer















    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.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 9 at 3:47

























    answered Mar 9 at 3:37









    DeadpoolDeadpool

    7,8322831




    7,8322831












    • So this looks like a tuple to me, if it is in python...

      – Code_Control_jxie0755
      Mar 9 at 3:41











    • yes exactly, but i have only limited knowledge in python @Code_Control_jxie0755

      – Deadpool
      Mar 9 at 3:42

















    • So this looks like a tuple to me, if it is in python...

      – Code_Control_jxie0755
      Mar 9 at 3:41











    • yes exactly, but i have only limited knowledge in python @Code_Control_jxie0755

      – Deadpool
      Mar 9 at 3:42
















    So this looks like a tuple to me, if it is in python...

    – Code_Control_jxie0755
    Mar 9 at 3:41





    So this looks like a tuple to me, if it is in python...

    – Code_Control_jxie0755
    Mar 9 at 3:41













    yes exactly, but i have only limited knowledge in python @Code_Control_jxie0755

    – Deadpool
    Mar 9 at 3:42





    yes exactly, but i have only limited knowledge in python @Code_Control_jxie0755

    – Deadpool
    Mar 9 at 3:42











    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.






    share|improve this answer





























      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.






      share|improve this answer



























        2












        2








        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.






        share|improve this answer















        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.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 9 at 4:30

























        answered Mar 9 at 3:53









        Basil BourqueBasil Bourque

        117k30397560




        117k30397560



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55073707%2fjava-list-of-method-is-quite-confusing%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived