Java TreeSet pollLast()方法及示例
Java.util.concurrent.TreeSet 的 pollLast() 方法是Java中的一个内置函数,它返回检索和删除最后(最高)的元素,如果这个集合是空的,则返回null。
语法
public E pollLast()
返回值: 该函数返回检索并删除最后(最高)的元素,如果这个集合是空的,则返回null。
下面的程序说明了TreeSet.pollLast()方法。
程序1 :
// Java program to demonstrate pollLast()
// method of TreeSet
import java.util.*;
class TreeSetpollLastExample1 {
public static void main(String[] args)
{
// Creating a set object
TreeSet<Integer> set
= new TreeSet<Integer>();
// Adding elements to this set
for (int i = 10; i <= 50; i += 10)
set.add(i);
// Printing the content of the set
System.out.println("Contents of the set: " + set);
// Retrieving and removing Last element of the set
System.out.println("The Last element of the set: "
+ set.pollLast());
// Printing the content of the set after pollLast()
System.out.println("Contents of the set after pollLast: "
+ set);
}
}
输出:
Contents of the set: [10, 20, 30, 40, 50]
The Last element of the set: 50
Contents of the set after pollLast: [10, 20, 30, 40]
程序2
// Java program to demonstrate pollLast()
// method of TreeSet
import java.util.*;
class TreeSetpollLastExample2 {
public static void main(String[] args)
{
// Creating a set object
TreeSet<Integer> set
= new TreeSet<Integer>();
// Printing the content of the set
System.out.println("Contents of the set: "
+ set);
// Retrieving and removing Last element of the set
System.out.println("The Last element of the set: "
+ set.pollLast());
}
}
输出:
Contents of the set: []
The Last element of the set: null
极客教程