本文小編為大家詳細介紹“Java中ArrayList和SubList的坑怎么解決”,內容詳細,步驟清晰,細節處理妥當,希望這篇“Java中ArrayList和SubList的坑怎么解決”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學習新知識吧。
不要,思考一下會打印出什么?
List<String> list1 = new ArrayList<>(Arrays.asList("username", "passwd"));
List<String> list2 = list1.subList(0, 2);
list2.add("email");
System.out.println(list1);
System.out.println(list2);執行結果:

你是否感覺疑惑?在想為什么在list2添加的在list1也添加是吧?
subList接口
List<E> subList(int fromIndex, int toIndex);
我們使用的是ArrayList,所以是選擇ArrayList即可
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
}fromIndex是從List元素開始索引,toIndex是List元素結束索引,subListRangeCheck方法是檢查是否在允許范圍之內。
static void subListRangeCheck(int fromIndex, int toIndex, int size) {
//開始索引小于0
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
//結束索引大于容量
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
//開始索引大于結束索引
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");重頭戲在new SubList(this, 0, fromIndex, toIndex);這里,看看下面的SubList就會知道,this關鍵字將當前對象的引用也就是list1傳入了SubList,把傳入的list1變成parent賦值給SubList內部成員,然后又將這個構造生成的賦值給list2,也就是說list1和list2是引用了同一個對象,指向的是同一list。
SubList(AbstractList<E> parent,
int offset, int fromIndex, int toIndex) {
//問題就出現在這里
this.parent = parent;
this.parentOffset = fromIndex;
this.offset = offset + fromIndex;
this.size = toIndex - fromIndex;
this.modCount = ArrayList.this.modCount;
}再來看看list2.add的源碼,將元素直接添加在list1和list2共同的list引用對象上,這就是為什么list2添加了,list1也添加了。
public void add(int index, E e) {
rangeCheckForAdd(index);
checkForComodification();
//將元素直接添加在list1和list2共同的list引用對象上
parent.add(parentOffset + index, e);
this.modCount = parent.modCount;
this.size++;
}subList(int fromIndex, int toIndex);
它返回原來list的從[fromIndex, toIndex)之間這一部分其實就是list的子列表(注意:fromIndex是 [ 說明包括其本身,toIndex是 )說明不包括其本身)。
這個子列表的本質其實還是原列表的一部分;也就是說,修改這個子列表,將導致原列表也發生改變。
舉例說明
list中包含1,2,3,4,5,6一共6個元素,list.subList(1,3)返回的是2,3(list以0為開始)
還有一個經常使用的list.subList(1,list.size)
list中包含1,2,3,4,5,6一共6個元素,list.subList(1,list.size)返回的是2,3,4,5,6(list以0為開始)
讀到這里,這篇“Java中ArrayList和SubList的坑怎么解決”文章已經介紹完畢,想要掌握這篇文章的知識點還需要大家自己動手實踐使用過才能領會,如果想了解更多相關內容的文章,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。