java sublist 用法_Java AbstractSequentialList.subList()用法及代码示例

Java中的AbstractSequentialList的subList()方法用于获取此列表在指定的fromIndex(包括)和toIndex(不包括)之间的部分的视图。 (如果fromIndex和toIndex相等,则返回列表为空。)此列表支持返回的列表,因此返回列表中的非结构性更改会反映在此列表中,反之亦然。返回的列表支持此列表支持的所有可选列表操作。

用法:

protected List subList(int fromIndex,

int toIndex)

参数:这些方法采用两个参数:

fromIndex:从中获取元素的起始索引。

toIndex:要从中获取元素的结束索引。(不包括)

返回值:此方法返回此列表内指定范围的视图

异常:该方法抛出:

IndexOutOfBoundsException:如果端点索引值超出范围。

IllegalArgumentException:如果端点索引不正确。

下面的示例说明AbstractSequentialList.subList()方法:

例子1:

// Java program to demonstrate the

// working of subList() method

import java.util.*;

public class GFG {

public static void main(String[] args)

{

// creating an AbstractSequentialList

AbstractSequentialList arr

= new LinkedList();

// use add() method

// to add values in the list

arr.add(1);

arr.add(2);

arr.add(3);

arr.add(12);

arr.add(9);

arr.add(13);

// prints the list before removing

System.out.println("AbstractSequentialList: "

+ arr);

// Getting subList of 1st 2 elements

// using subList() method

System.out.println("subList of 1st 2 elements: "

+ arr.subList(0, 2));

}

}

输出:

AbstractSequentialList: [1, 2, 3, 12, 9, 13]

subList of 1st 2 elements: [1, 2]

示例2:

// Java program to demonstrate the

// working of subList() method

import java.util.*;

public class GFG {

public static void main(String[] args)

{

// creating an AbstractSequentialList

AbstractSequentialList arr

= new LinkedList();

// use add() method

// to add values in the list

arr.add(1);

arr.add(2);

arr.add(3);

arr.add(12);

arr.add(9);

arr.add(13);

// prints the list before removing

System.out.println("AbstractSequentialList: "

+ arr);

System.out.println("Trying to get "

+ "subList of 11th elements: ");

try {

// Getting subList of 10th

// using subList() method

arr.subList(10, 11);

}

catch (Exception e) {

System.out.println(e);

}

}

}

输出:

AbstractSequentialList: [1, 2, 3, 12, 9, 13]

Trying to get subList of 11th elements:

java.lang.IndexOutOfBoundsException: toIndex = 11

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值