如何从Java中的列表中删除子列表
给定Java中的列表,任务是删除子列表中索引介于 fromIndex(包括)和 toIndex(不包括)之间的所有元素。索引的范围由用户定义。
例子:
Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4
Output [1, 2, 5, 6, 7, 8]
Input list = [‘G’, ‘E’, ‘E’, ‘G’, ‘G’, ‘K’, ‘S’], fromIndex = 3, endIndex = 5
Output [‘G’, ‘E’, ‘E’, ‘K’, ‘S’]
方法一:使用 subList() 和 clear() 方法
句法:
List.subList(int fromIndex, int toIndex).clear()
例子:
// Java code to remove a subList using // subList(a, b).clear() method import java.util.*; public class AbstractListDemo { public static void main(String args[]) { // Creating an empty AbstractList AbstractList
list = new LinkedList (); // Using add() method // to add elements in the list list.add("GFG"); list.add("for"); list.add("Geeks"); list.add("computer"); list.add("portal"); // Output the list System.out.println("Original List: " + list); // subList and clear method // to remove elements // specified in the range list.subList(1, 3).clear(); // Print the final list System.out.println("Final List: " + list); } } 输出:Original List: [GFG, for, Geeks, computer, portal] Final List: [GFG, computer, portal]
注意:可以继承 AbstractList 的类:
- 数组列表
- 向量
- 链表
- 堆
方法二:使用 removeRange() 方法
句法:
List.removeRange(int fromIndex, int toIndex)
例子:
// Java code to remove a subList // using removeRange() method import java.util.*; // since removeRange() is a protected method // ArrayList has to be extend the class public class GFG extends ArrayList
{ public static void main(String[] args) { // create an empty array list GFG arr = new GFG(); // use add() method // to add values in the list arr.add(1); arr.add(2); arr.add(3); arr.add(4); arr.add(5); arr.add(6); arr.add(7); arr.add(8); // prints the list before removing System.out.println("Original List: " + arr); // removing elements in the list // from index 2 to 4 arr.removeRange(2, 4); System.out.println("Final List: " + arr); } } 输出:Original List: [1, 2, 3, 4, 5, 6, 7, 8] Final List: [1, 2, 5, 6, 7, 8]