Java中的TreeSet pollLast()方法示例

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);
  
        // 获取并删除集合的最后一个元素
        System.out.println("The Last element of the set: "
                           + set.pollLast());
  
        // 在调用pollLast()后打印集合的内容
        System.out.println("Contents of the set after pollLast: "
                           + set);
    }
}
集合的内容:[10, 20, 30, 40, 50]
集合的最后一个元素:50
调用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>();
  
        // 打印集合的内容
        System.out.println("集合的内容:"
                           + set);
  
        // 获取并删除集合的最后一个元素
        System.out.println("集合的最后一个元素:"
                           + set.pollLast());
    }
}
集合的内容:[]
集合的最后一个元素:null

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程