Exception in thread main java.lang.UnsupportedOperationException

Exception in thread main java.lang.UnsupportedOperationException

If you see below exception means you are trying to modify fixed size array.

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.AbstractList.remove(Unknown Source)
	at java.util.AbstractList$Itr.remove(Unknown Source)
	at com.javahonk.unsupportedexception.UnsupportedException.main(UnsupportedException.java:23)

 

Below example will throw java.lang.UnsupportedOperationException:

package com.javahonk.unsupportedexception;

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

public class UnsupportedExceptionDemo {

	public static void main(String[] args) {

	String[] valStrings = { "Java", "Unsupported", "Test" };

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

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

	}

}

 

To fix it use LinkedList constructor and pass collection object as parameter shown below:

package com.javahonk.unsupportedexception;

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

public class UnsupportedException {

	public static void main(String[] args) {

	String[] strings = { "Java", "Unsupported", "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");

	}

}

Leave a Reply

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