📜  Java中的 TreeSet pollLast() 方法示例

📅  最后修改于: 2022-05-13 01:55:35.191000             🧑  作者: Mango

Java中的 TreeSet pollLast() 方法示例

Java .util.concurrent.TreeSetpollLast()方法是Java中的一个内置函数,它返回检索并删除最后一个(最高)元素,如果此集合为空,则返回 null。

句法:

public E pollLast()

返回值:该函数返回检索并删除最后一个(最高)元素,如果此集合为空,则返回 null。

下面的程序说明了 TreeSet.pollLast() 方法:

方案一:

// Java program to demonstrate pollLast()
// method of TreeSet
  
import java.util.*;
  
class TreeSetpollLastExample1 {
    public static void main(String[] args)
    {
        // Creating a set object
        TreeSet set
            = new TreeSet();
  
        // 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]

方案二:

// Java program to demonstrate pollLast()
// method of TreeSet
  
import java.util.*;
  
class TreeSetpollLastExample2 {
    public static void main(String[] args)
    {
        // Creating a set object
        TreeSet set
            = new TreeSet();
  
        // 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