How to solve Java List add – throwing java.lang.UnsupportedOperationException

Symptom:

You try to add an object to a list. But you get an Exception:

java.lang.UnsupportedOperationException
	at java.base/java.util.AbstractList.add(AbstractList.java:153)

Cause:

List<SomeEvent> eventList = Arrays.asList(event);
//not working, because the list size is fixed

Solution:

List<SomeEvent> eventList = new ArrayList<>(Arrays.asList(event));
//working, because the list size is NOT fixed

Of course, reading the Javadock of public static <T> List<T> asList(…) would have revealed it in advance:

/**
 * Returns a fixed-size list backed by the specified array.

;-D

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.