如何从Java列表中删除子列表?
从列表中删除子列表
假设我们列出了一些这样的元素,
list = [10,20,30,40,50]
从列表中,我们必须删除sourcing_index(包括)和destinating_index(排除)之间的子列表。
这可以通过两种方式完成:
通过使用接口的subList(intsourcing_index,intdestinating_index)和clear()方法。
通过使用List接口的removeRange(intsourcing_index,intdestinating_index)方法。
subList(intsourcing_index,intdestinating_index)和clear()List
此方法在列表接口中可用。
语法:
subList(int sourcing_index, int destinating_index);
我们在List方法中传递两个参数,
Sourcing_index是子列表起点的选择。
Destinating_index是子列表终点的选择。
示例
import java.util.*;
public class DeleteSublist {
public static void main(String[] args) {
LinkedList list = new LinkedList();
//使用add()方法在列表中添加元素
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
//当前列表输出
System.out.println("The Current list is:" + list);
//删除子列表
//和clear()列表的方法。
list.subList(2, 4).clear();
//新列表执行后输出
//subList()和clear()方法。
System.out.println("The New list is:" + list);
}
}输出结果
E:\Programs>javac DeleteSublist.java E:\Programs>java DeleteSublist The Current list is:[10, 20, 30, 40, 50] The New list is:[10, 20, 50]
removeRange(intsourcing_index,intdestinating_index)
此方法在列表接口中可用。
语法:
removeRange(int sourcing_index, int destinating_index);
我们在List方法中传递两个参数,
Sourcing_index是子列表起点的选择。
Destinating_index是子列表终点的选择。
示例
import java.util.*;
public class DeleteSublist extends LinkedList {
public static void main(String[] args) {
DeleteSublist list = new DeleteSublist();
//使用add()方法在列表中添加元素
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(50);
//当前列表输出
System.out.println("The Current list is:" + list);
//删除子列表
//列表的方法。
list.removeRange(2, 4);
//新列表执行后输出
//removeRange(int,int)方法。
System.out.println("The New list is:" + list);
}
}输出结果
E:\Programs>javac DeleteSublist.java E:\Programs>java DeleteSublist The Current list is:[10, 20, 30, 40, 50] The New list is:[10, 20, 50]
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短