Home » Java » Why SortedList.add() throws UnsupportedOperationException?

Why SortedList.add() throws UnsupportedOperationException?

Posted by: admin December 28, 2021 Leave a comment


Very simple code:

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;

public final class SortedListTest {

   public static void main( String[] args ) {
      final ObservableList<Integer> il  = FXCollections.observableArrayList();
      final SortedList<Integer>     sil = new SortedList<>( il );
      sil.comparatorProperty().set((l,r)-> l-r );
      sil.add( 12 );


Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at SortedListTest.main(SortedListTest.java:13)

A SortedList is a sorted view of its underlying list. If you were allowed to add elements to the sorted list it would break that relationship. You need to add the element to the underlying list instead: