Arrays.asList() throws java.lang.UnsupportedOperationException
You might get the UnsupportedException when you tries to use the add() method in the List.If your code looks something similar to this :
String[] data = new String[] {"hari","krushna"};
List<String> asList = Arrays.asList(data);
asList.add("test");
Then you will see the following exception :
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(Unknown Source)
at java.util.AbstractList.add(Unknown Source)
at ArrayConvert.trial(ArrayConvert.java:14)
at ArrayConvert.main(ArrayConvert.java:8)
Solution of the above problem is :
you need to create an ArrayList or LinkedList and add the objects to the newly created Array/LinkedList:
String[] data = new String[] {"","",""};
List<String> asList = Arrays.asList(data);
List<String> newList = new LinkedList<>(asList);
newList.add("test");
Reason for the UnsupportedOperationException:
Arrays.asList Method is returning a sub class object of Arrays class : java.util.Arrays.ArrayList
Following is the signature of the class :
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable
Here ArrayList extends java.util.AbstractList class.
Following are the add() method in AbstractList:
public boolean add(E e) {
add(size(), e);
return true;
}
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
This will be Runtime exception so difficult to identify at the time of coding.
Comments
Post a Comment