java 异常java.lang.UnsupportedOperationException
在项目中采用一个枚举的集合,本人采用Collections中的空集合Collections.emptyList()在添加时发生异常:
常见集合如下:
private List<VacationCategory> vacationcategorys = Collections.emptyList();
报错误如下:
-- Encapsulated exception ------------\
java.lang.UnsupportedOperationException
at java.util.AbstractList.add(AbstractList.java:131)
at java.util.AbstractList.add(AbstractList.java:91)
at
com.unutrip.callcenter.vacation.web.condition.VacationOrderConditionConvertor.setProductStyle(VacationOrderConditionConvertor.java:155)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
..............................
JDK API解释如下:
java.lang.CloneNotSupportedException
不支持克隆异常。当没有实现Cloneable接口或者不支持克隆方法时,调用其clone()方法则抛出该异常。
在网上查一下原因是因为部分集合类型一样但是缺少部分方法或不支持。
如特殊情况如下:
(1)常常使用Arrays.asLisvt()后调用add,remove这些method时出现java.lang.UnsupportedOperationException异常。这是由于:
Arrays.asLisvt()
返回java.util.Arrays$ArrayList,
而不是ArrayList。Arrays$ArrayList和ArrayList都是继承AbstractList,remove,add等
method在AbstractList中是默认throw
UnsupportedOperationException而且不作任何操作。ArrayList
override这些method来对list进行操作,但是Arrays$ArrayList没有override
remove(int),add(int)等,所以throw UnsupportedOperationException。
解决方法是使用Iterator,或者转换为ArrayList
List arrayList = new ArrayList(list);
(2)
private List<VacationCategory> vacationcategorys = Collections.emptyList();
执行remove,add等method时,抛出此异常,本人将上述代码改为:
private List<VacationCategory> vacationcategorys = new ArrayList<VacationCategory>();
没有此错误,于是我查看一下源代码:
源码如下:
此类在Collections的类中:
/**
* The empty list (immutable). This list is serializable.
*
* @see #emptyList()
*/
public static final List EMPTY_LIST = new EmptyList();
/**
* Returns the empty list (immutable). This list is serializable.
*
* <p>This example illustrates the type-safe way to obtain an empty list:
* <pre>
* List<String> s = Collections.emptyList();
* </pre>
* Implementation note: Implementations of this method need not
* create a separate <tt>List</tt> object for each call. Using this
* method is likely to have comparable cost to using the like-named
* field. (Unlike this method, the field does not provide type safety.)
*
* @see #EMPTY_LIST
* @since 1.5
*/
public static final <T> List<T> emptyList() {
return (List<T>) EMPTY_LIST;
}
/**
* @serial include
*/
private static class EmptyList
extends AbstractList<Object>
implements RandomAccess, Serializable {
// use serialVersionUID from JDK 1.2.2 for interoperability
private static final long serialVersionUID = 8842843931221139166L;
public int size() {return 0;}
public boolean contains(Object obj) {return false;}
public Object get(int index) {
throw new IndexOutOfBoundsException("Index: "+index);
}
// Preserves singleton property
private Object readResolve() {
return EMPTY_LIST;
}
}
EmptyList此集合竟然没有相应的add,remove等方法