Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add objects to List of Long

I want to add a Long Object to a List of Long, but I get some error that I don’t understand

I have the following minimal example:

package main;

import java.util.List;

public class Test {

    public static void main(String[] args) {
        
        List<Long> LongList = List.of((long) 3);
        LongList.add((long) 2);
    }

}

The Error msg is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)
at main.Test.main(Test.java:10)

I need to have the format Long, and I tried to change the way I convert to long. Also, I tried to give the position for where to add explicitly, but nothing changed.

>Solution :

From the documentation of List::of (docs.oracle.com):

Returns an unmodifiable list containing one element. See Unmodifiable Lists for details.

This is why the call to add(...) results in an UnsupportedOperationException. If we want to modify, the list created, we have to use a modifiable list, e.g.:

List<Long> LongList = new ArrayList<>(List.of((long) 3));
LongList.add((long) 2);

Ideone demo

or:

List<Long> LongList = new ArrayList<>();
LongList.add((long) 3);
LongList.add((long) 2);

Ideone demo


Some remarks on the code:

  • Variable names should be written in lowerCamelCase, not UpperCamelCase (LongList -> longList)
  • Instead of casting the literals 2 and 3 to long, we can use the long-literals 2L and 3L
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading