使用java.util.List.subList時最好小心點

來源:互聯網
上載者:User

java.util.List中有一個subList方法,用來返回一個list的一部分的視圖。

List<E> subList(int fromIndex, int toIndex);

它返回原來list的從[fromIndex, toIndex)之間這一部分的視圖,之所以說是視圖,是因為實際上,返回的list是靠原來的list支援的。

所以,你對原來的list和返回的list做的“非結構性修改”(non-structural changes),都會影響到彼此對方。

所謂的“非結構性修改”,是指不涉及到list的大小改變的修改。相反,結構性修改,指改變了list大小的修改。

 

那麼,如果涉及到結構性修改會怎麼樣呢?

如果發生結構性修改的是返回的子list,那麼原來的list的大小也會發生變化;

而如果發生結構性修改的是原來的list(不包括由於返回的子list導致的改變),那麼返回的子list語義上將會是undefined。在AbstractList(ArrayList的父類)中,undefined的具體表現形式是拋出一個ConcurrentModificationException。

因此,如果你在調用了sublist返回了子list之後,如果修改了原list的大小,那麼之前產生的子list將會失效,變得不可使用。

 

tips: 如何刪除一個list的某個區段,比如刪除list的第2-5個元素?

方法是: 可以利用sublist的幕後還是原來的list的這個特性,比如

list.subList(from, to).clear();

這樣就可以了。

 

範例程式碼: 

public static void main(String[] args) {        List<String> parentList = new ArrayList<String>();                for(int i = 0; i < 5; i++){            parentList.add(String.valueOf(i));        }                List<String> subList = parentList.subList(1, 3);        for(String s : subList){            System.out.println(s);//output: 1, 2        }                //non-structural modification by sublist, reflect parentList        subList.set(0, "new 1");         for(String s : parentList){            System.out.println(s);//output: 0, new 1, 2, 3, 4        }                //structural modification by sublist, reflect parentList        subList.add(String.valueOf(2.5));        for(String s : parentList){            System.out.println(s);//output:0, new 1, 2,    2.5, 3,    4        }                //non-structural modification by parentList, reflect sublist        parentList.set(2, "new 2");        for(String s : subList){            System.out.println(s);//output: new 1, new 2        }                //structural modification by parentList, sublist becomes undefined(throw exception)        parentList.add("undefine");//        for(String s : subList){//            System.out.println(s);//        }//        subList.get(0);    }

一個很有趣的思考:如何最高效的實現一個list的split方法?

參見:http://stackoverflow.com/questions/379551/java-split-a-list-into-two-sub-lists。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.