java.lang.UnsupportedOperationException List.clear 素颜马尾好姑娘i 2021-10-19 12:18 290阅读 0赞 用Set实现List去重的代码 public static <S> List<S> removeDedupElement(List<S> list) { TreeSet<S> set = new TreeSet<S>(list); list.clear(); list.addAll(set); return list; } 调用 System.out.println(removeDedupElement(Arrays.asList(new String[]{"qqq","qqq","www","www"}))); List<String> list = new LinkedList<String>(Arrays.asList(new String[]{"qqq","qqq","www","www"})); System.out.println(removeDedupElement(list)); 第一个会报错 at java.util.AbstractList.remove(AbstractList.java:161) at java.util.AbstractList$Itr.remove(AbstractList.java:374) at java.util.AbstractList.removeRange(AbstractList.java:571) at java.util.AbstractList.clear(AbstractList.java:234) at com.xxx.yyy.dqm.utils.CollectionUtils.removeDedupElement(LdBankCollectionUtils.java:10) 主要时由于Arrays.asList返回的是java.util.Arrays.ArrayList<E>, 这个跟java.util.ArrayList 都继承AbstractList ,但是java.util.Arrays.ArrayList<E>没有自己实现remove等方法, public E remove(int index) { throw new UnsupportedOperationException(); }
还没有评论,来说两句吧...