如何在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]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP