如何从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 送给学长毕业祝福语简短