What is UnsupportedOperationException

What is UnsupportedOperationException

UnsupportedOperationException is class which extends RuntimeException and this exception thrown to indicate that requested operation is not supported by API.

Reason is, when call java.util.Arrays.asList(String… a) method it returns fixed-size list backed by specified array so when you try to modify the list i.e. add or remove value from it will throw UnsupportedOperationException.

Below code will throw UnsupportedOperationException:

package com.javahonk.unsupported;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class UnsupportedException {

	public static void main(String[] args) {

	String[] strings = { "Java", "Honk", "Test" };

	List<String> list = Arrays.asList(strings);

	for (Iterator<String> iterator = 
			list.iterator(); iterator.hasNext();) {
		String string = iterator.next();
		iterator.remove();
	  }

	}

}

 

To fix UnsupportedOperationException use LinkedList constructor and pass collection object as parameter. Please see sample code below :

package com.javahonk.unsupported;

import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class UnsupportedExceptionFix {

	public static void main(String[] args) {

	String[] strings = { "Java", "Honk", "Test" };

	List<String> list2 = 
			new LinkedList<String>(Arrays.asList(strings));
	for (Iterator<String> iterator = 
			list2.iterator(); iterator.hasNext();) {
		String string = iterator.next();
		iterator.remove();
	}
	System.out.println("Removed all data from list");

	}

}

 

Please also check this post how to fix or use java concurrent package : exception-in-thread-main-java-util-concurrentmodificationexception

 

One thought on “What is UnsupportedOperationException”

Leave a Reply

Your email address will not be published. Required fields are marked *