如何在Java中從ArrayList中移除一個子列表?


使用subList()和clear()方法

List介面的**subList()**方法接受兩個整數值,表示元素的索引,並返回當前List物件的檢視,移除指定索引之間的元素。

List介面的**clear()**方法移除當前List物件中的所有元素。

因此,要移除ArrayList的特定子列表,只需在列表物件上呼叫這兩個方法,並指定要移除的子列表的邊界,例如:

obj.subList().clear();

示例

 線上演示

import java.util.ArrayList;
public class RemovingSubList {
   public static void main(String[] args){
      //Instantiating an ArrayList object
      ArrayList<String> list = new ArrayList<String>();
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the Array List: \n"+list);
      //Removing the sub list
      list.subList(4, 9).clear();
      System.out.println("Contents of the Array List after removing the sub list: \n"+list);
   }
}

輸出

Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the Array List after removing the sub list:
[JavaFX, Java, WebGL, OpenCV, Mahout, Impala]

使用removeRange()方法

AbstractList類的**removeRange()**方法接受兩個整數值,表示當前ArrayList元素的索引,並將其移除。

但這是一個受保護的方法,要使用它,需要:

  • 使用extends關鍵字繼承ArrayList類(來自你的類)。

  • 例項化你的類。

  • 向獲得的物件新增元素。

  • 然後,使用removeRange()方法移除所需的子列表。

示例

 線上演示

import java.util.ArrayList;
public class RemovingSubList extends ArrayList<String>{
   public static void main(String[] args){
      RemovingSubList list = new RemovingSubList();
      //Instantiating an ArrayList object
      list.add("JavaFX");
      list.add("Java");
      list.add("WebGL");
      list.add("OpenCV");
      list.add("OpenNLP");
      list.add("JOGL");
      list.add("Hadoop");
      list.add("HBase");
      list.add("Flume");
      list.add("Mahout");
      list.add("Impala");
      System.out.println("Contents of the Array List: \n"+list);
      //Removing the sub list
      list.removeRange(4, 9);
      System.out.println("Contents of the Array List after removing the sub list: \n"+list);
   }
}

輸出

Contents of the Array List:
[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]
Contents of the Array List after removing the sub list:
[JavaFX, Java, WebGL, OpenCV, Mahout, Impala]

更新於:2019年10月11日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告