AVt天堂网 手机版,亚洲va久久久噜噜噜久久4399,天天综合亚洲色在线精品,亚洲一级Av无码毛片久久精品

當前位置:首頁 > 科技  > 軟件

Java|List.subList 踩坑小記

來源: 責編: 時間:2023-09-22 20:11:39 265觀看
導讀很久以前在使用 Java 的 List.subList 方法時踩過一個坑,當時記了一條待辦,要寫一寫這事,今天完成它。我們先來看一段代碼:// 初始化 list 為 { 1, 2, 3, 4, 5 }List<Integer> list = new ArrayList<>();for (int i = 1;

HSL28資訊網——每日最新資訊28at.com

很久以前在使用 Java 的 List.subList 方法時踩過一個坑,當時記了一條待辦,要寫一寫這事,今天完成它。HSL28資訊網——每日最新資訊28at.com

我們先來看一段代碼:HSL28資訊網——每日最新資訊28at.com

// 初始化 list 為 { 1, 2, 3, 4, 5 }List<Integer> list = new ArrayList<>();for (int i = 1; i <= 5; i++) {    list.add(i);}// 取前 3 個元素作為 subList,操作 subListList<Integer> subList = list.subList(0, 3);subList.add(6);System.out.println(list.size());

輸出是 5 還是 6?HSL28資訊網——每日最新資訊28at.com

沒踩過坑的我,會回答是 5,理由是:往一個 List 里加元素,關其它 List 什么事?HSL28資訊網——每日最新資訊28at.com

而掉過坑的我,口中直呼 666。HSL28資訊網——每日最新資訊28at.com

好了不繞彎子,我們直接看下 List.subList 方法的注釋文檔:HSL28資訊網——每日最新資訊28at.com

/** * Returns a view of the portion of this list between the specified * <tt>fromIndex</tt>, inclusive, and <tt>toIndex</tt>, exclusive.  (If * <tt>fromIndex</tt> and <tt>toIndex</tt> are equal, the returned list is * empty.)  The returned list is backed by this list, so non-structural * changes in the returned list are reflected in this list, and vice-versa. * The returned list supports all of the optional list operations supported * by this list.<p> * * This method eliminates the need for explicit range operations (of * the sort that commonly exist for arrays).  Any operation that expects * a list can be used as a range operation by passing a subList view * instead of a whole list.  For example, the following idiom * removes a range of elements from a list: * <pre>{@code *      list.subList(from, to).clear(); * }</pre> * Similar idioms may be constructed for <tt>indexOf</tt> and * <tt>lastIndexOf</tt>, and all of the algorithms in the * <tt>Collections</tt> class can be applied to a subList.<p> * * The semantics of the list returned by this method become undefined if * the backing list (i.e., this list) is <i>structurally modified</i> in * any way other than via the returned list.  (Structural modifications are * those that change the size of this list, or otherwise perturb it in such * a fashion that iterations in progress may yield incorrect results.) * * @param fromIndex low endpoint (inclusive) of the subList * @param toIndex high endpoint (exclusive) of the subList * @return a view of the specified range within this list * @throws IndexOutOfBoundsException for an illegal endpoint index value *         (<tt>fromIndex < 0 || toIndex > size || *         fromIndex > toIndex</tt>) */List<E> subList(int fromIndex, int toIndex);

這里面有幾個要點:HSL28資訊網——每日最新資訊28at.com

subList 返回的是原 List 的一個 視圖,而不是一個新的 List,所以對 subList 的操作會反映到原 List 上,反之亦然;HSL28資訊網——每日最新資訊28at.com

如果原 List 在 subList 操作期間發生了結構修改,那么 subList 的行為就是未定義的(實際表現為拋異常)。HSL28資訊網——每日最新資訊28at.com

第一點好理解,看到「視圖」這個詞相信大家就都能理解了。我們甚至可以結合 ArrayList 里的 SubList 子類源碼進一步看下:HSL28資訊網——每日最新資訊28at.com

private class SubList extends AbstractList<E> implements RandomAccess {    private final AbstractList<E> parent;    // ...    SubList(AbstractList<E> parent,            int offset, int fromIndex, int toIndex) {        this.parent = parent;        // ...        this.modCount = ArrayList.this.modCount;    }    public E set(int index, E e) {        // ...        checkForComodification();        // ...        ArrayList.this.elementData[offset + index] = e;        // ...    }    public E get(int index) {        // ...        checkForComodification();        return ArrayList.this.elementData(offset + index);    }    public void add(int index, E e) {        // ...        checkForComodification();        parent.add(parentOffset + index, e);        this.modCount = parent.modCount;        // ...    }    public E remove(int index) {        // ...        checkForComodification();        E result = parent.remove(parentOffset + index);        this.modCount = parent.modCount;        // ...    }    private void checkForComodification() {        if (ArrayList.this.modCount != this.modCount)            throw new ConcurrentModificationException();    }    // ...}

可以看到幾乎所有的讀寫操作都是映射到 ArrayList.this、或者 parent(即原 List)上的,包括 size、add、remove、set、get、removeRange、addAll 等等。HSL28資訊網——每日最新資訊28at.com

第二點,我們在文首的示例代碼里加上兩句代碼看現象:HSL28資訊網——每日最新資訊28at.com

list.add(0, 0);System.out.println(subList);

System.out.println 會拋出異常 java.util.ConcurrentModificationException。HSL28資訊網——每日最新資訊28at.com

我們還可以試下,在聲明 subList 后,如果對原 List 進行元素增刪操作,然后再讀寫 subList,基本都會拋出此異常。HSL28資訊網——每日最新資訊28at.com

因為 subList 里的所有讀寫操作里都調用了 checkForComodification(),這個方法里檢驗了 subList 和 List 的 modCount 字段值是否相等,如果不相等則拋出異常。HSL28資訊網——每日最新資訊28at.com

modCount 字段定義在 AbstractList 中,記錄所屬 List 發生 結構修改 的次數。結構修改 包括修改 List 大小(如 add、remove 等)、或者會使正在進行的迭代器操作出錯的修改(如 sort、replaceAll 等)。HSL28資訊網——每日最新資訊28at.com

好了小結一下,這其實不算是坑,只是 不應該僅憑印象和猜測,就開始使用一個方法,至少花一分鐘認真讀完它的官方注釋文檔。HSL28資訊網——每日最新資訊28at.com

本文鏈接:http://www.tebozhan.com/showinfo-26-11204-0.htmlJava|List.subList 踩坑小記

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 基于Python+Flask實現一個簡易網頁驗證碼登錄系統案例

下一篇: 網絡安全:滲透測試工程師必備的十種技能

標簽:
  • 熱門焦點
  • Find N3入網:最高支持16+1TB

    OPPO將于近期登場的Find N3折疊屏目前已經正式入網,型號為PHN110。本次Find N3在外觀方面相比前兩代有很大的變化,不再是小號的橫向折疊屏,而是跟別的廠商一樣采用了較為常見的
  • 對標蘋果的靈動島 華為帶來實況窗功能

    繼蘋果的靈動島之后,華為也在今天正式推出了“實況窗”功能。據今天鴻蒙OS 4.0的現場演示顯示,華為的實況窗可以更高效的展現出實時通知,比如鎖屏上就能看到外賣、打車、銀行
  • 6月安卓手機好評榜:魅族20 Pro蟬聯冠軍

    性能榜和性價比榜之后,我們來看最后的安卓手機好評榜,數據來源安兔兔評測,收集時間2023年6月1日至6月30日,僅限國內市場。第一名:魅族20 Pro好評率:95%5月份的時候魅族20 Pro就是
  • 得物效率前端微應用推進過程與思考

    一、背景效率工程隨著業務的發展,組織規模的擴大,越來越多的企業開始意識到協作效率對于企業團隊的重要性,甚至是決定其在某個行業競爭中突圍的關鍵,是企業長久生存的根本。得物
  • “又被陳思誠騙了”

    作者|張思齊 出品|眾面(ID:ZhongMian_ZM)如今的國產懸疑電影,成了陳思誠的天下。最近大爆電影《消失的她》票房突破30億斷層奪魁暑期檔,陳思誠再度風頭無兩。你可以說陳思誠的
  • 質感不錯!OPPO K11渲染圖曝光:旗艦IMX890傳感器首次下放

    一直以來,OPPO K系列機型都保持著較為均衡的產品體驗,歷來都是2K價位的明星機型,去年推出的OPPO K10和OPPO K10 Pro兩款機型憑借各自的出色配置,堪稱有
  • onebot M24巧系列一體機采用輕薄機身設計,現已在各平臺開售

    onebot M24 巧系列一體機目前已在線上線下各平臺同步開售。onebot M24 巧系列采用一體化輕薄機身設計,最薄處為 10.15mm,擁有寶石紅、午夜藍、石墨綠、雅致
  • AI藝術欣賞體驗會在上海梅賽德斯奔馳中心音樂俱樂部上演

    光影交錯的鏡像世界,虛實幻化的視覺奇觀,虛擬偶像與真人共同主持,這些場景都出現在2019世界人工智能大會的舞臺上。8月29日至31日,“AI藝術欣賞體驗會”在上海
  • 中關村論壇11月25日開幕,15位諾獎級大咖將發表演講

    11月18日,記者從2022中關村論壇新聞發布會上獲悉,中關村論壇將于11月25至30日在京舉行。本屆中關村論壇由科學技術部、國家發展改革委、工業和信息化部、國務
Top