Java的ConcurrentSkipListSet subSet() 方法及其示例
java.util.concurrent.ConcurrentSkipListSet 的 subSet() 方法是Java的内置函数,它返回由此方法定义的区间中的元素。
函数的语法清晰地说明了指定元素,后跟示例。
语法:
subSet(E fromElement, E toElement)
或
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
参数:
第一种变体的该方法带有两个参数,定义了将返回的元素的范围。toElement 不包括在返回集合中。
第二种变体与第一种类似,但是这里的布尔参数明确地包括或排除 toElement 和 fromElement。
返回:
第一种方法变体返回此集合的部分视图,其元素范围从 fromElement(包括)到 toElement(不包括)。
第二种方法变体返回此集合的部分视图,其元素范围从 fromElement 到 toElements,由布尔包容参数定义。
异常:
空指针异常: 如果指定的元素为 NULL。
下面是演示Java中的ConcurrentSkipListSet subSet() 的示例程序:
示例1:
返回从30000到90000的元素,但不包括90000。
// Java program to demonstrate ConcurrentSkipListSet subSet() method
import java.util.concurrent.ConcurrentSkipListSet;
class ConcurrentSkipListSetExample {
public static void main(String[] args)
{
// Initializing the set using ConcurrentSkipListSet()
ConcurrentSkipListSet<Integer>
set = new ConcurrentSkipListSet<Integer>();
// Adding elements to this set
set.add(65552);
set.add(34324);
set.add(93423);
set.add(41523);
set.add(90000);
// Printing the ConcurrentSkipListSet
System.out.println("ConcurrentSkipListSet: "
+ set);
// Printing the elements of ConcurrentSkipListSet that
// are returned by subSet() method
System.out.println("The returned elements are: "
+ set.subSet(30000, 90000));
}
}
输出:
ConcurrentSkipListSet: [34324, 41523, 65552, 90000, 93423]
The returned elements are: [34324, 41523, 65552]
示例2:
在此示例中,元素400也被返回,因为布尔包容是true。
// Java程序,演示ConcurrentSkipListSet subSet()方法
import java.util.concurrent.ConcurrentSkipListSet;
class ConcurrentSkipListSetExample {
public static void main(String[] args)
{
// 使用ConcurrentSkipListSet()初始化一个集合
ConcurrentSkipListSet<Integer>
set = new ConcurrentSkipListSet<Integer>();
// 往集合中添加元素
set.add(652);
set.add(324);
set.add(400);
set.add(123);
set.add(200);
// 打印ConcurrentSkipListSet
System.out.println("ConcurrentSkipListSet: "
+ set);
// 打印通过subSet()方法返回的ConcurrentSkipListSet的元素
System.out.println("The returned elements are: "
+ set.subSet(100, true, 400, true));
}
}
输出:
ConcurrentSkipListSet: [123, 200, 324, 400, 652]
The returned elements are: [123, 200, 324, 400]
极客教程