在项目中用了Arrays.asList、ArrayList的subList,被公开批评
点击下方“IT牧场”,选择“设为星标”
来源:http://nxw.so/4UaLX
1. 使用Arrays.asList的注意事项
1.1 可能会踩的坑
List<Integer> statusList = Arrays.asList(1, 2);
System.out.println(statusList);
System.out.println(statusList.contains(1));
System.out.println(statusList.contains(3));
statusList.add(3);
System.out.println(statusList.contains(3));
1.2 原因分析
1.3 总结
2. 使用ArrayList的subList的注意事项
List<String> bookList = new ArrayList<>();
bookList.add("遥远的救世主");
bookList.add("背叛");
bookList.add("天幕红尘");
bookList.add("人生");
bookList.add("平凡的世界");
List<String> luyaoBookList = bookList.subList(3, 5);
System.out.println(bookList);
System.out.println(luyaoBookList);
2.1 修改原集合的值,会影响子集合
List<String> bookList = new ArrayList<>();
bookList.add("遥远的救世主");
bookList.add("背叛");
bookList.add("天幕红尘");
bookList.add("人生");
bookList.add("平凡的世界");
List<String> luyaoBookList = bookList.subList(3, 5);
System.out.println(bookList);
System.out.println(luyaoBookList);
// 修改原集合的值
bookList.set(3,"路遥-人生");
System.out.println(bookList);
System.out.println(luyaoBookList);
2.2 修改原集合的结构,会引起ConcurrentModificationException
异常
List<String> bookList = new ArrayList<>();
bookList.add("遥远的救世主");
bookList.add("背叛");
bookList.add("天幕红尘");
bookList.add("人生");
bookList.add("平凡的世界");
List<String> luyaoBookList = bookList.subList(3, 5);
System.out.println(bookList);
System.out.println(luyaoBookList);
// 往原集合中添加元素
bookList.add("早晨从中午开始");
System.out.println(bookList);
System.out.println(luyaoBookList);
2.3 修改子集合的值,会影响原集合
List<String> bookList = new ArrayList<>();
bookList.add("遥远的救世主");
bookList.add("背叛");
bookList.add("天幕红尘");
bookList.add("人生");
bookList.add("平凡的世界");
List<String> luyaoBookList = bookList.subList(3, 5);
System.out.println(bookList);
System.out.println(luyaoBookList);
// 修改子集合的值
luyaoBookList.set(1,"路遥-平凡的世界");
System.out.println(bookList);
System.out.println(luyaoBookList);
2.4 修改子集合的结构,会影响原集合
List<String> bookList = new ArrayList<>();
bookList.add("遥远的救世主");
bookList.add("背叛");
bookList.add("天幕红尘");
bookList.add("人生");
bookList.add("平凡的世界");
List<String> luyaoBookList = bookList.subList(3, 5);
System.out.println(bookList);
System.out.println(luyaoBookList);
// 往子集合中添加元素
luyaoBookList.add("早晨从中午开始");
System.out.println(bookList);
System.out.println(luyaoBookList);
2.5 原因分析
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}
2.6 总结
干货分享
最近将个人学习笔记整理成册,使用PDF分享。关注我,回复如下代码,即可获得百度盘地址,无套路领取!
•001:《Java并发与高并发解决方案》学习笔记;•002:《深入JVM内核——原理、诊断与优化》学习笔记;•003:《Java面试宝典》•004:《Docker开源书》•005:《Kubernetes开源书》•006:《DDD速成(领域驱动设计速成)》•007:全部•008:加技术群讨论
关注我
喜欢就点个"在看"呗^_^
评论