Search code examples
javacollections

i'm getting an Exception in thread "main" java.lang.UnsupportedOperationException


The environment details i'm running my program :

java version "17.0.7" 2023-04-18 LTS Java(TM) SE Runtime Environment (build 17.0.7+8-LTS-224) Java HotSpot(TM) 64-Bit Server VM (build 17.0.7+8-LTS-224, mixed mode, sharing)

Program:

public class Conversions {

    public static void main(String[] args) {
        
        List<Integer> lIn = new ArrayList<>();
        lIn.add(4);
        lIn.add(56);
        lIn.add(423);
        lIn.add(2516);
        lIn.add(924);
        lIn.add(5611);

        //ArrayList to Array
        int[] conArray = lIn.stream().mapToInt(i -> i).toArray();
        
        
        // Array to ArrayList
        
        int[] arr = {5,8,9,34,63,119};
        List<Integer> convList = Arrays.stream(arr).boxed().toList();
        System.out.println(convList);    //30   
                                         //31
        Collections.sort(convList);      //32
        Collections.reverse(convList);   //33

    }

}

Error:

Exception in thread "main" java.lang.UnsupportedOperationException at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142) at java.base/java.util.ImmutableCollections$AbstractImmutableList.sort(ImmutableCollections.java:261) at java.base/java.util.Collections.sort(Collections.java:145) at com.example.DependencyInjection.Conversions.main**(Conversions.java:32)

I'm trying to understand why the compiler is throwing UnsupportedOperationException even though i'm using the Collections.sort() method correctly . All I'm doing is passing a list but still I'm getting the exception.


Solution

  • The list returned by .toList() (a method of Stream) is immutable. Sorting it (.sort()) sorts 'in place' and this requires mutating the list. You can't do that.

    The usual fix is to first copy the immutable list into a mutable one: convList = new ArrayList<Integer>(convList);.

    However, all of your code is a bit suspect. Why go from int[] to List<Integer> to Stream and back again?

    EDIT: Let's just leave 'I want to go from one to another' as written - instead of making a list and then trying to sort the list, instead sort the stream as it 'runs':

    List<Integer> convList = Arrays.stream(arr)
      .sorted()  // Add this!
      .boxed()
      .toArray();