Why does the following code throw UnsupportedOperationException
?
import javafx.beans.property.MapProperty;
import javafx.beans.property.SimpleMapProperty;
public class TestMapProperty {
static MapProperty<String, String> model = new SimpleMapProperty<String, String>();
public static void main(String[] args) {
model.put("blue", "green"); // exception thrown here
}
}
Stack trace:
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:203)
at javafx.beans.binding.MapExpression.put(MapExpression.java:277)
at TestMapProperty.main(TestMapProperty.java:10)
What is java.lang.UnsupportedOperationException? java.lang.UnsupportedOperationException is thrown to denote that the requested operation is not supported by the underlying collection object. The List object returned by the asList method of the Arrays class is unmodifiable.
The UnsupportedOperationException indicates that the requested operation cannot be performed, due to the fact that it is forbidden for that particular class. The following methods create unmodifiable views of different collections: Returns an unmodifiable view of the specified Collection.
The remove method of an Iterator class may throw UnsupportedOperationException if the iterator is obtained from an unmodifiable List object (like given in the above example) and the method is called while iterating over the list. 1 2 3
This exception extends the RuntimeException class and thus, belongs to those exceptions that can be thrown during the operation of the Java Virtual Machine (JVM). It is an unchecked exception and thus, it does not need to be declared in a method’s or a constructor’s throws clause.
The answer from Pace is still valid, but if you want a Property and not only an ObservableMap, then this is not the correct code.
static MapProperty<String, String> model = new SimpleMapProperty<String, String>(FXCollections.observableHashMap());
will fit more. You still have to initialize the SimpleMapProperty with a new ObservableMap instance. The constructors without an initial Map of SimpleMapProperty won't create one for you. This is because you may choose your own implementation of an ObservableMap for backing the Property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With