在项目中用了Arrays.asList、ArrayList的subList,被公开批评
来源: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 总结
评论