1. 程式人生 > >List 中subList 慎用(減法陷阱)

List 中subList 慎用(減法陷阱)

查詢java原始碼我們可以看到:tempList的subList實現程式碼在AbstractList類裡邊,然而無論如何,最終 的結果都是返回一個AbstractList的子類:SubList(該類是一個使用預設修飾符修飾的類,其原始碼位於 AbstractList.java類檔案裡邊),

SubList類的構造方法:
SubList(AbstractList 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;
expectedModCount = l.modCount;
}

上面的解釋通俗的講就是,將原來的list賦值給了l,隨後將遊標移動。所以這兩個變數的指向是同一個地址,當我們修改l的值,也就修改了指向的那個地址的值,原來的list值就發生了變化。

我們用一個測試類來測試下:
List list = new ArrayList();
for(int i = 0; i<10 ;i++){
list.add(i);
}
System.out.println(list);
List tempList = list.subList(0, 4);
System.out.println(tempList);
tempList.clear();
for(int i = 1; i<5 ;i++){
tempList.add(i);
}
System.out.println(tempList);
System.out.println(list);
測試結果為:
測試結果


地址圖解釋:
地址描述
這就說明了一個問題,以後慎用sublist。