Java中的ConcurrentSkipListSet lower()方法及示例
ConcurrentSkipListSet 的 lower() 方法用于返回该集合中严格小于指定元素的最大元素。如果集合中没有这样的元素,则此函数将返回 null。
语法:
public E lower (E e)
参数: 此方法仅接受一个参数,即指定要匹配的值 e。
返回值: 此方法返回一个值,该值是集合中严格小于指定元素的最大元素。如果不存在这样的元素,则返回 Null。
异常: 此方法会引发以下异常:
- ClassCastException: 如果此集合中的元素类与指定的集合不兼容,则会抛出此异常。
- NullPointerException: 如果指定的集合为 null,则会抛出此异常。
以下程序说明了 ConcurrentSkipListSet 类的 lower() 函数:
程序 1: 在下面的程序中,指定的元素是67,我们的集合也包含元素67,但它没有被返回,因为 lower() 方法返回严格小于的值。
// Java program to demonstrate
// ConcurrentSkipListSet lower() method.
import java.util.concurrent.ConcurrentSkipListSet;
class GfgCSLS {
public static void main(String[] args)
{
// Initializing the set
// using ConcurrentSkipListSet()
ConcurrentSkipListSet<Integer>
set = new ConcurrentSkipListSet<Integer>();
// Adding elements to this set
// using add() method
set.add(17);
set.add(24);
set.add(35);
set.add(67);
set.add(98);
// Printing the ConcurrentSkipListSet
System.out.println("ConcurrentSkipListSet: "
+ set);
// Invoking lower() method
// to find the largest element
// less than the specified element
System.out.println("Largest element: "
+ set.lower(67));
}
}
输出:
ConcurrentSkipListSet: [17, 24, 35, 67, 98]
Largest element: 35
程序 2: 展示 NullPointerException
// Java program to demonstrate
// ConcurrentSkipListSet lower() method.
import java.util.concurrent.ConcurrentSkipListSet;
class GfgCSLS {
public static void main(String[] args)
{
// Initializing the set
// using ConcurrentSkipListSet()
ConcurrentSkipListSet<Integer>
set = new ConcurrentSkipListSet<Integer>();
// Adding elements to this set
// using add() method
set.add(17);
set.add(24);
set.add(35);
set.add(67);
set.add(98);
// Printing the ConcurrentSkipListSet
System.out.println("ConcurrentSkipListSet: "
+ set);
try {
// Invoking lower() method
// to find the largest element
// less than the specified element
System.out.println("Largest element: "
+ set.lower(null));
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
ConcurrentSkipListSet: [17, 24, 35, 67, 98]
java.lang.NullPointerException
极客教程