java.lang.UnsupportedOperationException异常的原因和解决办法

it2023-02-04  51

java.lang.UnsupportedOperationException异常的原因和解决办法

在项目中对List进行操作时报错java.lang.UnsupportedOperationException,后来发现操作的List是由数组转换而成的,通过看源码发现问题如下: 代码块:

private String[] strList = {"1","2","3","4","5","6","7","8","9","10","11","12","13"}; @Override public void run() { List<String> syncStrList = Collections.synchronizedList(Arrays.asList(strList)); if(Thread.currentThread().getName().equals("线程=1")) { syncStrList.add(0, "你好");

执行结果:

Exception in thread “线程=2” Exception in thread “线程=1” java.lang.UnsupportedOperationException at java.util.AbstractList.add(Unknown Source) at java.util.Collections S y n c h r o n i z e d L i s t . a d d ( U n k n o w n S o u r c e ) a t c o m . a o k i . t e s t . M T h r e a d . r u n ( M u t i T h r e a d 4 L i s t . j a v a : 38 ) a t j a v a . l a n g . T h r e a d . r u n ( U n k n o w n S o u r c e ) j a v a . l a n g . U n s u p p o r t e d O p e r a t i o n E x c e p t i o n a t j a v a . u t i l . A b s t r a c t L i s t . r e m o v e ( U n k n o w n S o u r c e ) a t j a v a . u t i l . C o l l e c t i o n s SynchronizedList.add(Unknown Source) at com.aoki.test.MThread.run(MutiThread4List.java:38) at java.lang.Thread.run(Unknown Source) java.lang.UnsupportedOperationException at java.util.AbstractList.remove(Unknown Source) at java.util.Collections SynchronizedList.add(UnknownSource)atcom.aoki.test.MThread.run(MutiThread4List.java:38)atjava.lang.Thread.run(UnknownSource)java.lang.UnsupportedOperationExceptionatjava.util.AbstractList.remove(UnknownSource)atjava.util.CollectionsSynchronizedList.remove(Unknown Source) at com.aoki.test.MThread.run(MutiThread4List.java:45) at java.lang.Thread.run(Unknown Source)

发生问题的原因如下: 调用Arrays.asList()生产的List的add、remove方法时报异常,这是由Arrays.asList() 返回的市Arrays的内部类ArrayList, 而不是java.util.ArrayList。Arrays的内部类ArrayList和java.util.ArrayList都是继承AbstractList,remove、add等方法AbstractList中是默认throw UnsupportedOperationException而且不作任何操作。java.util.ArrayList重新了这些方法而Arrays的内部类ArrayList没有重新,所以会抛出异常。解决方法如下:

List<String> syncStrList =new ArrayList<>(Collections.synchronizedList(Arrays.asList(strList)));
最新回复(0)