Java中subList的問題

我們經常使用subString方法來對String對象進行分割處理,同時我們也可以使用subList、subMap、subSet來對List、Map、Set進行分割處理,但是這個分割存在某些瑕疵。

一、subList返回僅僅只是一個視圖

        首先我們先看如下實例:

  1. public static void main(String[] args) {  
  2.         List<Integer> list1 = new ArrayList<Integer>();  
  3.         list1.add(1);  
  4.         list1.add(2);  
  5.           
  6.         //通過構造函數新建一個包含list1的列表 list2  
  7.         List<Integer> list2 = new ArrayList<Integer>(list1);  
  8.           
  9.         //通過subList生成一個與list1一樣的列表 list3  
  10.         List<Integer> list3 = list1.subList(0, list1.size());  
  11.           
  12.         //修改list3  
  13.         list3.add(3);  
  14.           
  15.         System.out.println("list1 == list2:" + list1.equals(list2));  
  16.         System.out.println("list1 == list3:" + list1.equals(list3));  
  17.     }  

        這個例子非常簡單,無非就是通過構造函數、subList重新生成一個與list1一樣的list,然後修改list3,最後比較list1 == list2?、list1 == list3?。按照我們常規的思路應該是這樣的:因爲list3通過add新增了一個元素,那麼它肯定與list1不等,而list2是通過list1構造出來的,所以應該相等,所以結果應該是:

  1. list1 == list2:true  
  2. list1 == list3: false  

        首先我們先不論結果的正確與否,我們先看subList的源碼:

  1. public List<E> subList(int fromIndex, int toIndex) {  
  2.         subListRangeCheck(fromIndex, toIndex, size);  
  3.         return new SubList(this0, fromIndex, toIndex);  
  4.     }  

        subListRangeCheck方式是判斷fromIndex、toIndex是否合法,如果合法就直接返回一個subList對象,注意在產生該new該對象的時候傳遞了一個參數 this ,該參數非常重要,因爲他代表着原始list。

  1. /** 
  2.      * 繼承AbstractList類,實現RandomAccess接口 
  3.      */  
  4.     private class SubList extends AbstractList<E> implements RandomAccess {  
  5.         private final AbstractList<E> parent;    //列表  
  6.         private final int parentOffset;     
  7.         private final int offset;  
  8.         int size;  
  9.   
  10.         //構造函數  
  11.         SubList(AbstractList<E> parent,  
  12.                 int offset, int fromIndex, int toIndex) {  
  13.             this.parent = parent;  
  14.             this.parentOffset = fromIndex;  
  15.             this.offset = offset + fromIndex;  
  16.             this.size = toIndex - fromIndex;  
  17.             this.modCount = ArrayList.this.modCount;  
  18.         }  
  19.   
  20.         //set方法  
  21.         public E set(int index, E e) {  
  22.             rangeCheck(index);  
  23.             checkForComodification();  
  24.             E oldValue = ArrayList.this.elementData(offset + index);  
  25.             ArrayList.this.elementData[offset + index] = e;  
  26.             return oldValue;  
  27.         }  
  28.   
  29.         //get方法  
  30.         public E get(int index) {  
  31.             rangeCheck(index);  
  32.             checkForComodification();  
  33.             return ArrayList.this.elementData(offset + index);  
  34.         }  
  35.   
  36.         //add方法  
  37.         public void add(int index, E e) {  
  38.             rangeCheckForAdd(index);  
  39.             checkForComodification();  
  40.             parent.add(parentOffset + index, e);  
  41.             this.modCount = parent.modCount;  
  42.             this.size++;  
  43.         }  
  44.   
  45.         //remove方法  
  46.         public E remove(int index) {  
  47.             rangeCheck(index);  
  48.             checkForComodification();  
  49.             E result = parent.remove(parentOffset + index);  
  50.             this.modCount = parent.modCount;  
  51.             this.size--;  
  52.             return result;  
  53.         }  
  54.     }  

        該SubLsit是ArrayList的內部類,它與ArrayList一樣,都是繼承AbstractList和實現RandomAccess接口。同時也提供了get、set、add、remove等list常用的方法。但是它的構造函數有點特殊,在該構造函數中有兩個地方需要注意:

        1、this.parent = parent;而parent就是在前面傳遞過來的list,也就是說this.parent就是原始list的引用。

        2、this.offset = offset + fromIndex;this.parentOffset = fromIndex;。同時在構造函數中它甚至將modCount(fail-fast機制)傳遞過來了。

        我們再看get方法,在get方法中return ArrayList.this.elementData(offset + index);這段代碼可以清晰表明get所返回就是原列表offset + index位置的元素。同樣的道理還有add方法裏面的:

  1. parent.add(parentOffset + index, e);  
  2. this.modCount = parent.modCount;  

        remove方法裏面的

  1. E result = parent.remove(parentOffset + index);  
  2. this.modCount = parent.modCount;  

        誠然,到了這裏我們可以判斷subList返回的SubList同樣也是AbstractList的子類,同時它的方法如get、set、add、remove等都是在原列表上面做操作,它並沒有像subString一樣生成一個新的對象。所以subList返回的只是原列表的一個視圖,它所有的操作最終都會作用在原列表上。

        那麼從這裏的分析我們可以得出上面的結果應該恰恰與我們上面的答案相反:

  1. list1 == list2:false  
  2. list1 == list3:true  

Java細節(3.1):subList返回的只是原列表的一個視圖,它所有的操作最終都會作用在原列表上

二、subList生成子列表後,不要試圖去操作原列表

        從上面我們知道subList生成的子列表只是原列表的一個視圖而已,如果我們操作子列表它產生的作用都會在原列表上面表現,但是如果我們操作原列表會產生什麼情況呢?

  1. public static void main(String[] args) {  
  2.         List<Integer> list1 = new ArrayList<Integer>();  
  3.         list1.add(1);  
  4.         list1.add(2);  
  5.           
  6.         //通過subList生成一個與list1一樣的列表 list3  
  7.         List<Integer> list3 = list1.subList(0, list1.size());  
  8.         //修改list3  
  9.         list1.add(3);  
  10.           
  11.         System.out.println("list1'size:" + list1.size());  
  12.         System.out.println("list3'size:" + list3.size());  
  13.     }  

        該實例如果不產生意外,那麼他們兩個list的大小都應該都是3,但是偏偏事與願違,事實上我們得到的結果是這樣的:

  1. list1'size:3  
  2. Exception in thread "main" java.util.ConcurrentModificationException  
  3.     at java.util.ArrayList$SubList.checkForComodification(Unknown Source)  
  4.     at java.util.ArrayList$SubList.size(Unknown Source)  
  5.     at com.chenssy.test.arrayList.SubListTest.main(SubListTest.java:17)  

        list1正常輸出,但是list3就拋出ConcurrentModificationException異常,看過我另一篇博客的同仁肯定對這個異常非常,fail-fast?不錯就是fail-fast機制,在fail-fast機制中,LZ花了很多力氣來講述這個異常,所以這裏LZ就不對這個異常多講了(更多請點這裏:Java提高篇(三四)—–fail-fast機制)。我們再看size方法:

  1. public int size() {  
  2.             checkForComodification();  
  3.             return this.size;  
  4.         }  

        size方法首先會通過checkForComodification驗證,然後再返回this.size。

  1. private void checkForComodification() {  
  2.             if (ArrayList.this.modCount != this.modCount)  
  3.                 throw new ConcurrentModificationException();  
  4.         }  

        該方法表明當原列表的modCount與this.modCount不相等時就會拋出ConcurrentModificationException。同時我們知道modCount 在new的過程中 “繼承”了原列表modCount,只有在修改該列表(子列表)時纔會修改該值(先表現在原列表後作用於子列表)。而在該實例中我們是操作原列表,原列表的modCount當然不會反應在子列表的modCount上啦,所以纔會拋出該異常。

        對於子列表視圖,它是動態生成的,生成之後就不要操作原列表了,否則必然都導致視圖的不穩定而拋出異常。最好的辦法就是將原列表設置爲只讀狀態,要操作就操作子列表:

  1. //通過subList生成一個與list1一樣的列表 list3  
  2. List<Integer> list3 = list1.subList(0, list1.size());  
  3.           
  4. //對list1設置爲只讀狀態  
  5. list1 = Collections.unmodifiableList(list1);  

Java細節(3.2):生成子列表後,不要試圖去操作原列表,否則會造成子列表的不穩定而產生異常

三、推薦使用subList處理局部列表

        在開發過程中我們一定會遇到這樣一個問題:獲取一堆數據後,需要刪除某段數據。例如,有一個列表存在1000條記錄,我們需要刪除100-200位置處的數據,可能我們會這樣處理:

  1. for(int i = 0 ; i < list1.size() ; i++){  
  2.    if(i >= 100 && i <= 200){  
  3.        list1.remove(i);  
  4.        /* 
  5.         * 當然這段代碼存在問題,list remove之後後面的元素會填充上來, 
  6.          * 所以需要對i進行簡單的處理,當然這個不是這裏討論的問題。 
  7.          */  
  8.    }  
  9. }  

        這個應該是我們大部分人的處理方式吧,其實還有更好的方法,利用subList。在前面LZ已經講過,子列表的操作都會反映在原列表上。所以下面一行代碼全部搞定:

  1. list1.subList(100200).clear();  

簡單而不失華麗!!!!!

發佈了260 篇原創文章 · 獲贊 53 · 訪問量 125萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章