List数组遍历删除
环境
- jdk8
- junit 单元测试
正解
// 正解1, jdk自带的addAll方法
@Test
public void test18() {
String[] strs = {"12","34","56","78","90"};
List<String> list = Arrays.asList(strs);
List<String> list2 = new ArrayList<>();
list2.addAll(list);
System.out.println(list);
for (String s : list) {
System.out.println(s);
list2.remove(s);
}
}
// 正解2 Hutool的 CollUtil 工具类中addAll方法
@Test
public void test18() {
String[] strs = {"12","34","56","78","90"};
List<String> list = Arrays.asList(strs);
List<String> list2 = new ArrayList<>();
CollUtil.addAll(list2,list);
System.out.println(list2);
for (String s : list) {
System.out.println(s);
list2.remove(s);
}
}
boolean b = list1.removeIf(a -> (a % 2) == 0);
System.out.println(b);
错解
新手代码踩坑日记
// 第一错
@Test
public void test18() {
String[] strs = {"12","34","56","78","90"};
List<String> list = Arrays.asList(strs);
System.out.println(list);
for (String s : list) {
System.out.println(s);
list.remove(s);
}
}
报错信息:
[12, 34, 56, 78, 90]
12
java.lang.UnsupportedOperationException 不支持的操作异常
at java.util.AbstractList.remove(AbstractList.java:161)
at java.util.AbstractList$Itr.remove(AbstractList.java:374)
at java.util.AbstractCollection.remove(AbstractCollection.java:293)
// 第二错 : 老子新建个对象来存还是错??? 仔细想想-->TMD谁写的垃圾代码,好像是我写的...
// 方法栈里面就一个list对象,只是复制一份引用,而remove是直接操作数组内存空间
@Test
public void test18() {
String[] strs = {"12","34","56","78","90"};
List<String> list = Arrays.asList(strs);
List<String> list2 = new ArrayList<>();
list2 = list;
System.out.println(list);
for (String s : list) {
System.out.println(s);
list2.remove(s);
}
}
直接报错 +1:
[12, 34, 56, 78, 90]
12
java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at java.util.AbstractList$Itr.remove(AbstractList.java:374)
at java.util.AbstractCollection.remove(AbstractCollection.java:293)