在平時,需要取出集合中一部分數據時。通常會使用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
ArrayList.subList
返回的是其內部類 SubList 的實例(原始列表的一個視圖)。
對原來的list和返回的list做的“非結構性修改”(non-structural changes),都會影響到對方。
所謂的“非結構性修改”是指不涉及到list的大小改變的修改。相反,結構性修改,指改變了list大小的修改。
- 如果發生結構性修改的是返回的子list,那么原來的list的大小也會發生變化;
- 而如果發生結構性修改的是原來的list(不包括由於返回的子list導致的改變),那么返回的子list語義上將會是undefined。在AbstractList(ArrayList的父類)中,undefined的具體表現形式是拋出一個ConcurrentModificationException。
這也很好理解,在Java的繼承體系中,父類永遠不知道自己有沒有/有多少子類。
取出來的子集長度只有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
強調:使用sublist()返回的只是原list對象的一個視圖,因此Sublist內部類和ArrayList的內部保存數據的地址是一樣得;即它們在內存中是同一個List(集合),只是parentOffset ,size等參數不同
1.如果達到的效果要對子集進行操作,原始list不改變。建議以下方式:
List<Object> tempList = new ArrayList<Object>(list.subList(2, lists.size()));
tempList.add("xxxxx");
2.我們可以方便的使用如下代碼來刪除某個區間的序列。
list.subList(from, to).clear();
--------------------- 本文來自 ypp91zr 的CSDN 博客 ,全文地址請點擊:https://blog.csdn.net/ypp91zr/article/details/52117814?utm_source=copy