日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

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

Java|List.subList 踩坑小記

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

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

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

我們先來看一段代碼:bda28資訊網——每日最新資訊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?bda28資訊網——每日最新資訊28at.com

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

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

好了不繞彎子,我們直接看下 List.subList 方法的注釋文檔:bda28資訊網——每日最新資訊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);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

標簽:
  • 熱門焦點
  • 紅魔電競平板評測:大屏幕硬實力

    前言:三年的疫情因為要上網課的原因激活了平板市場,如今網課的時代已經過去,大家的生活都恢復到了正軌,這也就意味著,真正考驗平板電腦生存的環境來了。也就是面對著這種殘酷的
  • 帥氣純真少年!日本最帥初中生選美冠軍出爐

    日本第一帥哥初一生選美大賽冠軍現已正式出爐,冠軍是來自千葉縣的宗田悠良。日本一直熱衷于各種選美大賽,從&ldquo;最美JK&rdquo;起到&ldquo;最美女星&r
  • 如何正確使用:Has和:Nth-Last-Child

    我們可以用CSS檢查,以了解一組元素的數量是否小于或等于一個數字。例如,一個擁有三個或更多子項的grid。你可能會想,為什么需要這樣做呢?在某些情況下,一個組件或一個布局可能會
  • 得物效率前端微應用推進過程與思考

    一、背景效率工程隨著業務的發展,組織規模的擴大,越來越多的企業開始意識到協作效率對于企業團隊的重要性,甚至是決定其在某個行業競爭中突圍的關鍵,是企業長久生存的根本。得物
  • 三萬字盤點 Spring 九大核心基礎功能

    大家好,我是三友~~今天來跟大家聊一聊Spring的9大核心基礎功能。話不多說,先上目錄:圖片友情提示,本文過長,建議收藏,嘿嘿嘿!一、資源管理資源管理是Spring的一個核心的基礎功能,不
  • 每天一道面試題-CPU偽共享

    前言:了不起:又到了每天一到面試題的時候了!學弟,最近學習的怎么樣啊 了不起學弟:最近學習的還不錯,每天都在學習,每天都在進步! 了不起:那你最近學習的什么呢? 了不起學弟:最近在學習C
  • 雅柏威士忌多款單品價格大跌,泥煤頂流也不香了?

    來源 | 烈酒商業觀察編 | 肖海林今年以來,威士忌市場開始出現了降溫跡象,越來越多不斷暴漲的網紅威士忌也開始悄然回歸市場理性。近日,LVMH集團旗下蘇格蘭威士忌品牌雅柏(Ardbeg
  • 華為舉行春季智慧辦公新品發布會 首次推出電子墨水屏平板

    北京時間2月27日晚,華為在巴塞羅那舉行春季智慧辦公新品發布會,在海外市場推出之前已經在中國市場上市的筆記本、平板、激光打印機等辦公產品,并首次推出搭載
  • 電博會與軟博會實現"線下+云端"的雙線融合

    在本次“電博會”與“軟博會”雙展會利好條件的加持下,既可以發揮展會拉動人流、信息流、資金流實現快速交互流動的作用,繼而推動區域經濟良性發展;又可以聚
Top 主站蜘蛛池模板: 靖西县| 岳普湖县| 科尔| 霍林郭勒市| 齐河县| 济源市| 双峰县| 潜江市| 金门县| 麟游县| 蛟河市| 云安县| 肥东县| 神农架林区| 安远县| 神木县| 邓州市| 德保县| 阳山县| 德钦县| 千阳县| 彰化市| 嘉峪关市| 翁源县| 孝昌县| 湛江市| 金乡县| 营山县| 鹤峰县| 大厂| 正安县| 福建省| 开远市| 兰考县| 陵川县| 昭通市| 珲春市| 凤冈县| 长海县| 扶风县| 遵化市|