Java中ArrayList和SubList的坑面試題
代碼復現(xiàn)
不要,思考一下會打印出什么?
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);
執(zhí)行結果:
你是否感覺疑惑?在想為什么在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方法是檢查是否在允許范圍之內(nèi)。
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內(nèi)部成員,然后又將這個構造生成的賦值給list2,也就是說list1和list2是引用了同一個對象,指向的是同一list。
SubList(AbstractList<E> parent, int offset, int fromIndex, int toIndex) { //問題就出現(xiàn)在這里 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++; }
附:ArrayList的subList簡單介紹和使用
subList(int fromIndex, int toIndex);
它返回原來list的從[fromIndex, toIndex)之間這一部分其實就是list的子列表(注意:fromIndex是 [ 說明包括其本身,toIndex是 )說明不包括其本身)。
這個子列表的本質(zhì)其實還是原列表的一部分;也就是說,修改這個子列表,將導致原列表也發(fā)生改變。
舉例說明
list中包含1,2,3,4,5,6一共6個元素,list.subList(1,3)返回的是2,3(list以0為開始)
還有一個經(jīng)常使用的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的坑面試題的文章就介紹到這了,更多相關ArrayList和SubList面試題內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
如何在springboot中配置和使用mybatis-plus
這篇文章主要給大家介紹了關于如何在springboot中配置和使用mybatis-plus的相關資料,MyBatis?Plus是MyBatis的增強版,旨在提供更多便捷的特性,減少開發(fā)工作,同時保留了MyBatis的靈活性和強大性能,需要的朋友可以參考下2023-11-11Java實現(xiàn)常用加密算法——單向加密算法MD5和SHA
本篇文章主要介紹了Java實現(xiàn)常用加密算法——單向加密算法MD5和SHA,信息加密后數(shù)據(jù)更安全,需要的朋友可以參考下。2016-10-10