关于ArrayList 中 subList 方法的陷阱
在平时,需要取出集合中一部分数据时。通常会使用subList
举个例子:
List<String> list=new ArrayList<>(); list.add("d"); list.add("33"); list.add("44"); list.add("55"); list.add("66"); List<String> list2 = list.subList(0, 2); System.out.println(list.size());//5 System.out.println(list2.size());//2
取出来的子集长度只有2.查看源代码。
public List<E> subList(int fromIndex, int toIndex) { return (this instanceof RandomAccess ? new RandomAccessSubList<>(this, fromIndex, toIndex) : new SubList<>(this, fromIndex, toIndex)); }注意这里传的this非常重要,直接将原始list传进去了
.........
跟到最后都是SubList<E>
class SubList<E> extends AbstractList<E> { private final AbstractList<E> l; private final int offset; private int size; SubList(AbstractList<E> list, int fromIndex, int toIndex) { if (fromIndex < 0) throw new IndexOutOfBoundsException("fromIndex = " + fromIndex); if (toIndex > list.size()) throw new IndexOutOfBoundsException("toIndex = " + toIndex); if (fromIndex > toIndex) throw new IllegalArgumentException("fromIndex(" + fromIndex + ") > toIndex(" + toIndex + ")"); l = list; offset = fromIndex; size = toIndex - fromIndex; this.modCount = l.modCount; } public E set(int index, E element) { rangeCheck(index); checkForComodification(); return l.set(index+offset, element); } public E get(int index) { rangeCheck(index); checkForComodification(); return l.get(index+offset); } public int size() { checkForComodification(); return size; } public void add(int index, E element) { rangeCheckForAdd(index); checkForComodification(); l.add(index+offset, element); this.modCount = l.modCount; size++; }
将原始list赋给SubList<E>中的AbstractList<E> l;然而截取的子集长度是size = toIndex - fromIndex;
其实就是到toIndex-1索引的值,举例:list.subList(0, 2)。不是0、1、2三个,子集只是索引0和1的值
大家注意在进行子集add等方法的时候都进行了AbstractList<E> l的操作。所以出现了下面的情况,子集添加时原始list也进行了增加
List<String> list=new ArrayList<>(); list.add("d"); list.add("33"); list.add("44"); list.add("55"); list.add("66"); List<String> list2 = list.subList(0, 2); list2.add("77"); System.out.println(list.size());//6 System.out.println(list2.size());//3
如果达到的效果要对子集进行操作,原始list不改变。建议以下方式:
List<Object> tempList = new ArrayList<Object>(list.subList(2, lists.size()));
tempList.add("xxxxx");
声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。