Java中的 ConcurrentSkipListSet subSet() 方法及示例
Java .util.concurrent.ConcurrentSkipListSet的subSet()方法是Java中的一个内置函数,其中元素在此方法定义的范围内返回。
该函数的语法给出了对指定元素的清晰理解,后面是示例。
句法:
subSet(E fromElement, E toElement)
or
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)
参数:
此方法的第一个变体采用两个参数,它们定义了将要返回的元素的范围。 toElement 不包含在返回的集合中。
第二个变体类似于第一个变体,但这里的布尔参数特别包括或排除了 toElement 和 fromElement。
回报:
第一个方法变体返回此集合的一部分的视图,其元素范围从 fromElement(包括)到 toElement(不包括)。
第二种方法变体返回此集合的一部分的视图,其元素范围从 fromElement 到 toElements,由布尔包含参数定义。
例外:
空指针异常:如果指定的元素为空。
以下是说明Java中的 ConcurrentSkipListSet subSet() 的示例程序:
示例:1
返回从 30000 到 90000 的元素,但不包括 90000。
Java
// 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
set = new ConcurrentSkipListSet();
// 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));
}
}
Java
// 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
set = new ConcurrentSkipListSet();
// Adding elements to this set
set.add(652);
set.add(324);
set.add(400);
set.add(123);
set.add(200);
// 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(100, true, 400, true));
}
}
输出:
ConcurrentSkipListSet: [34324, 41523, 65552, 90000, 93423]
The returned elements are: [34324, 41523, 65552]
示例:2
在这个例子中,元素 400 也被返回,因为 boolean inclusive 为真。
Java
// 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
set = new ConcurrentSkipListSet();
// Adding elements to this set
set.add(652);
set.add(324);
set.add(400);
set.add(123);
set.add(200);
// 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(100, true, 400, true));
}
}
输出:
ConcurrentSkipListSet: [123, 200, 324, 400, 652]
The returned elements are: [123, 200, 324, 400]