最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

java ArrayList.remove()的三種錯誤用法以及六種正確用法詳解

 更新時間:2020年01月03日 15:19:40   作者:逆水_行舟  
這篇文章主要介紹了java ArrayList.remove()的三種錯誤用法以及六種正確用法詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧

java集合中,list列表應(yīng)該是我們最常使用的,它有兩種常見的實現(xiàn)類:ArrayList和LinkedList。ArrayList底層是數(shù)組,查找比較方便;LinkedList底層是鏈表,更適合做新增和刪除。但實際開發(fā)中,我們也會遇到使用ArrayList需要刪除列表元素的時候。雖然ArrayList類已經(jīng)提供了remove方法,不過其中有潛在的坑,下面將介紹remove方法的三種錯誤用法以及六種正確用法。

1、錯誤用法

1.1、for循環(huán)中使用remove(int index),列表從前往后遍歷

首先看一下ArrayList.remove(int index)的源碼,讀代碼前先看方法注釋:移除列表指定位置的一個元素,將該元素后面的元素們往左移動一位。返回被移除的元素。

源代碼也比較好理解,ArrayList底層是數(shù)組,size是數(shù)組長度大小,index是數(shù)組索引坐標(biāo),modCount是被修改次數(shù)的計數(shù)器,oldValue就是被移除索引的元素對象,numMoved是需要移動的元素數(shù)量,如果numMoved大于0,則執(zhí)行一個數(shù)組拷貝(實質(zhì)是被移除元素后面的元素都向前移動一位)。然后數(shù)組長度size減少1,列表最后一位元素置為空。最后將被移除的元素對象返回。

  /**
   * Removes the element at the specified position in this list.
   * Shifts any subsequent elements to the left (subtracts one from their
   * indices).
   *
   * @param index the index of the element to be removed
   * @return the element that was removed from the list
   * @throws IndexOutOfBoundsException {@inheritDoc}
   */
  public E remove(int index) {
    rangeCheck(index);
 
    modCount++;
    E oldValue = elementData(index);
 
    int numMoved = size - index - 1;
    if (numMoved > 0)
      System.arraycopy(elementData, index+1, elementData, index,
               numMoved);
    elementData[--size] = null; // clear to let GC do its work
 
    return oldValue;
  }

如果在for循環(huán)中調(diào)用了多次ArrayList.remove(),那代碼執(zhí)行結(jié)果是不準(zhǔn)確的,因為每次每次調(diào)用remove函數(shù),ArrayList列表都會改變數(shù)組長度,被移除元素后面的元素位置都會發(fā)生變化。比如下面這個例子,本來是想把列表中奇數(shù)位置的元素都移除,但最終得到的結(jié)果是[2,3,5]。

    List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 3L, 4L, 5L));
    for (int i = 0; i < list.size(); i++) {
      if (i % 2 == 0) {
        list.remove(i);
      }
    }
    //最終得到[2,3,5]

1.2、直接使用list.remove(Object o)

ArrayList.remove(Object o)源碼的邏輯和ArrayList.remove(int index)大致相同:列表索引坐標(biāo)從小到大循環(huán)遍歷,若列表中存在與入?yún)ο笙嗟鹊脑?,則把該元素移除,后面的元素都往左移動一位,返回true,若不存在與入?yún)⑾嗟鹊脑?,返回false。

  public boolean remove(Object o) {
    if (o == null) {
      for (int index = 0; index < size; index++)
        if (elementData[index] == null) {
          fastRemove(index);
          return true;
        }
    } else {
      for (int index = 0; index < size; index++)
        if (o.equals(elementData[index])) {
          fastRemove(index);
          return true;
        }
    }
    return false;
  }
 
  /*
   * Private remove method that skips bounds checking and does not
   * return the value removed.
   */
  private void fastRemove(int index) {
    modCount++;
    int numMoved = size - index - 1;
    if (numMoved > 0)
      System.arraycopy(elementData, index+1, elementData, index,
               numMoved);
    elementData[--size] = null; // clear to let GC do its work
  }

如果直接對list調(diào)用了該方法,代碼結(jié)果可能會不準(zhǔn)確。例子如下:這段代碼本想移除列表中全部值為2的元素,結(jié)果并沒有成功。

    List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 2L, 4L, 5L));
    list.remove(2L);
    //最終得到[1,2,4,5]

1.3、Arrays.asList()之后使用remove()

為啥使用了Arrays.asList()之后使用remove是錯誤用法,我們看一下asList()的源碼就能知道了。Arrays.asList()返回的是一個指定數(shù)組長度的列表,所以不能做Add、Remove等操作。至于為啥是返回的是固定長度的,看下面源碼,asList()函數(shù)中調(diào)用的new ArrayList<>()并不是我們常用的ArrayList類,而是一個Arrays的內(nèi)部類,也叫ArrayList,而且這個內(nèi)部類也是基于數(shù)組實現(xiàn)的,但它有一個明顯的關(guān)鍵字修飾,那就是final。都用final修飾了,那是肯定不能再對它進(jìn)行add/remove操作的。如果非要在Arrays.asList之后使用remove,正確用法參見2.5。

  public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
  }
 
  private static class ArrayList<E> extends AbstractList<E>
    implements RandomAccess, java.io.Serializable
   {
    private static final long serialVersionUID = -2764017481108945198L;
    private final E[] a;
 
    ArrayList(E[] array) {
      a = Objects.requireNonNull(array);
    }
  }

2、正確用法

2.1、直接使用removeIf()

使用removeIf()這個方法前,我是有點害怕的,畢竟前面兩個remove方法都不能直接使用。于是小心翼翼的看了removeIf函數(shù)的方法。確認(rèn)過源碼,是我想要的方法!

源碼如下:removeIf()的入?yún)⑹且粋€過濾條件,用來判斷需要移除的元素是否滿足條件。方法中設(shè)置了一個removeSet,把滿足條件的元素索引坐標(biāo)都放入removeSet,然后統(tǒng)一對removeSet中的索引進(jìn)行移除。源碼相對復(fù)雜的是BitSet模型,源碼這里不再貼了。

public boolean removeIf(Predicate<? super E> filter) {
    Objects.requireNonNull(filter);
    // figure out which elements are to be removed
    // any exception thrown from the filter predicate at this stage
    // will leave the collection unmodified
    int removeCount = 0;
    final BitSet removeSet = new BitSet(size);
    final int expectedModCount = modCount;
    final int size = this.size;
    for (int i=0; modCount == expectedModCount && i < size; i++) {
      @SuppressWarnings("unchecked")
      final E element = (E) elementData[i];
      if (filter.test(element)) {
        removeSet.set(i);
        removeCount++;
      }
    }
    if (modCount != expectedModCount) {
      throw new ConcurrentModificationException();
    }
 
    // shift surviving elements left over the spaces left by removed elements
    final boolean anyToRemove = removeCount > 0;
    if (anyToRemove) {
      final int newSize = size - removeCount;
      for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
        i = removeSet.nextClearBit(i);
        elementData[j] = elementData[i];
      }
      for (int k=newSize; k < size; k++) {
        elementData[k] = null; // Let gc do its work
      }
      this.size = newSize;
      if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
      }
      modCount++;
    }
 
    return anyToRemove;
  }

removeIf()的使用方法如下所示(jdk8),結(jié)果滿足預(yù)期。

  List<Long> list = new ArrayList<>(Arrays.asList(1L, 2L, 2L, 4L, 5L));
  list.removeIf(val -> val == 2L);
  //結(jié)果得到[1L,4L,5L]

2.2、在for循環(huán)之后使用removeAll(Collection<?> c)

這種方法思路是for循環(huán)內(nèi)使用一個集合存放所有滿足移除條件的元素,for循環(huán)結(jié)束后直接使用removeAll方法進(jìn)行移除。removeAll源碼如下,還是比較好理解的:定義了兩個數(shù)組指針r和w,初始都指向列表第一個元素。循環(huán)遍歷列表,r指向當(dāng)前元素,若當(dāng)前元素沒有滿足移除條件,將數(shù)組[r]元素賦值給數(shù)組[w],w指針向后移動一位。這樣就完成了整個數(shù)組中,沒有被移除的元素向前移動。遍歷完列表后,將w后面的元素都置空,并減少數(shù)組長度。至此完成removeAll移除操作。

public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    return batchRemove(c, false);
  }
 
private boolean batchRemove(Collection<?> c, boolean complement) {
    final Object[] elementData = this.elementData;
    int r = 0, w = 0;
    boolean modified = false;
    try {
      for (; r < size; r++)
        if (c.contains(elementData[r]) == complement)
          elementData[w++] = elementData[r];
    } finally {
      // Preserve behavioral compatibility with AbstractCollection,
      // even if c.contains() throws.
      if (r != size) {
        System.arraycopy(elementData, r,
                 elementData, w,
                 size - r);
        w += size - r;
      }
      if (w != size) {
        // clear to let GC do its work
        for (int i = w; i < size; i++)
          elementData[i] = null;
        modCount += size - w;
        size = w;
        modified = true;
      }
    }
    return modified;
  }

正確使用方式如下:

List<Long> removeList = new ArrayList<>();
    for (int i = 0; i < list.size(); i++) {
      if (i % 2 == 0) {
        removeList.add(list.get(i));
      }
    }
    list.removeAll(removeList);

2.3、list轉(zhuǎn)為迭代器Iterator的方式

迭代器就是一個鏈表,直接使用remove操作不會出現(xiàn)問題。

Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
 if (it.next() % 2 == 0)
 it.remove();
}

2.4、for循環(huán)中使用remove(int index), 列表從后往前遍歷

前面1.1也是for循環(huán),為啥從后往前遍歷就是正確的呢。因為每次調(diào)用remove(int index),index后面的元素會往前移動,如果是從后往前遍歷,index后面的元素發(fā)生移動,跟index前面的元素?zé)o關(guān),我們循環(huán)只去和前面的元素做判斷,因此就沒有影響。

for (int i = list.size() - 1; i >= 0; i--) {
      if (list.get(i).longValue() == 2) {
        list.remove(i);
      }
    }

2.5、Arrays.asList()之后使用remove()

Arrays.asList()之后需要進(jìn)行add/remove操作,可以使用下面這種方式:

String[] arr = new String[3];
List list = new ArrayList(Arrays.asList(arr));

2.6、使用while循環(huán)

使用while循環(huán),刪除了元素,索引便不+1,在沒刪除元素時索引+1

int i=0;
while (i<list.size()) {
 if (i % 2 == 0) {
 list.remove(i);
 }else {
 i++;
 }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java讀取xml文件的五種方式

    Java讀取xml文件的五種方式

    在編寫與 XML 數(shù)據(jù)交互的現(xiàn)代軟件應(yīng)用時,有效地讀取和解析 XML 文件是至關(guān)重要的,本文旨在探討 Java 中處理 XML 文件的五種主要方法:DOM、SAX、StAX、JAXB 和 JDOM,我們將詳細(xì)介紹每種方法的工作原理、典型用途以及如何在 Java 程序中實現(xiàn)它們
    2024-05-05
  • Spring Boot 項目創(chuàng)建的詳細(xì)步驟(圖文)

    Spring Boot 項目創(chuàng)建的詳細(xì)步驟(圖文)

    這篇文章主要介紹了Spring Boot 項目創(chuàng)建的詳細(xì)步驟(圖文),這里我們有兩種創(chuàng)建Spring Boot項目的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-05-05
  • 詳解Java如何獲取文件編碼格式

    詳解Java如何獲取文件編碼格式

    這篇文章主要介紹了詳解Java如何獲取文件編碼格式,具有一定的參考價值,感興趣的小伙伴們可以參考一下。
    2017-01-01
  • Spring?MVC各種參數(shù)進(jìn)行封裝的方法實例

    Spring?MVC各種參數(shù)進(jìn)行封裝的方法實例

    這篇文章主要給大家介紹了關(guān)于Spring?MVC各種參數(shù)進(jìn)行封裝的相關(guān)資料,SpringMVC內(nèi)置多種數(shù)據(jù)類型轉(zhuǎn)換器,可以根據(jù)請求中的參數(shù)與后端控制器方法的參數(shù)的關(guān)系為我們實現(xiàn)簡單的數(shù)據(jù)封裝,需要的朋友可以參考下
    2023-06-06
  • 解決java -jar XXX.jar沒有主清單屬性以及找不到或無法加載主類的問題

    解決java -jar XXX.jar沒有主清單屬性以及找不到或無法加載主類的問題

    在使用Idea打包SpringBoot項目時,可能會遇到“沒有主清單屬性”的錯誤,問題原因是pom文件中缺少配置,未能正確打包成可執(zhí)行的jar,解決方法包括:1. 修改項目結(jié)構(gòu)并重新生成jar;2. 使用Maven插件在pom文件中添加spring-boot-maven-plugin配置
    2024-09-09
  • Spring Boot 中的 @Field 注解的原理解析

    Spring Boot 中的 @Field 注解的原理解析

    本文詳細(xì)介紹了 Spring Boot 中的 @Field 注解的原理和使用方法,通過使用 @Field 注解,我們可以將 HTTP 請求中的參數(shù)值自動綁定到 Java 對象的屬性上,簡化了開發(fā)過程,提高了開發(fā)效率,感興趣的朋友跟隨小編一起看看吧
    2023-07-07
  • Windows 下安裝配置 Eclipse詳細(xì)教程

    Windows 下安裝配置 Eclipse詳細(xì)教程

    Eclipse是一款非常優(yōu)秀的開源IDE,非常適合Java開發(fā),由于支持插件技術(shù),受到了越來越多的開發(fā)者的歡迎。配合眾多令人眼花繚亂的插件,完全可以滿足從企業(yè)級Java應(yīng)用到手機終端Java游戲的開發(fā)。本文將帶您手把手步入Eclipse的廣闊天地
    2016-09-09
  • IDEA如何修改配置文件的存放位置

    IDEA如何修改配置文件的存放位置

    這篇文章主要介紹了IDEA如何修改配置文件的存放位置,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-12-12
  • springcloud項目快速開始起始模板的實現(xiàn)

    springcloud項目快速開始起始模板的實現(xiàn)

    本文主要介紹了springcloud項目快速開始起始模板思路的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-12-12
  • maven 刪除下載失敗的包的方法

    maven 刪除下載失敗的包的方法

    本文介紹了當(dāng)Maven包報紅時,使用刪除相關(guān)文件的方法來解決該問題,具有一定的參考價值,感興趣的可以了解一下
    2023-09-09

最新評論

冀州市| 方正县| 中宁县| 漠河县| 三都| 卫辉市| 广昌县| 吉木乃县| 松潘县| 涿州市| 子洲县| 襄樊市| 磐石市| 五华县| 富民县| 宣武区| 白玉县| 那曲县| 阳城县| 垦利县| 北川| 阜阳市| 河池市| 景德镇市| 丹阳市| 武陟县| 达孜县| 肥乡县| 紫金县| 衡南县| 赣榆县| 东海县| 柳河县| 兴安盟| 洛宁县| 西林县| 蒙城县| 渝北区| 加查县| 永泰县| 横峰县|