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:
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);
or:
List<Long> LongList = new ArrayList<>();
LongList.add((long) 3);
LongList.add((long) 2);
Some remarks on the code:
- Variable names should be written in
lowerCamelCase, notUpperCamelCase(LongList->longList) - Instead of casting the literals
2and3tolong, we can use thelong-literals2Land3L