Java中的 TreeSet pollFirst() 方法
Java中 TreeSet 的 pollFirst() 方法用于检索和删除第一个(最低)元素,如果此 TreeSet 为空,则返回 null。
句法:
E pollFirst()
其中,E 是此 TreeSet 容器维护的元素的类型。
参数:此函数不接受任何参数。
返回类型:如果 TreeSet 不为空,则返回 Treeset 的第一个元素,否则返回 null。
下面的程序说明了Java中的 pollFirst() 方法:
示例 1
// A Java program to demonstrate
// pollFirst() method of TreeSet
import java.util.TreeSet;
public class GFG {
public static void main(String[] args)
{
// creating TreeSet
TreeSet ts = new TreeSet();
// adding element to the TreeSet
ts.add(0);
ts.add(1);
ts.add(2);
ts.add(3);
ts.add(4);
ts.add(5);
ts.add(6);
// before removing element
System.out.println("Before removing " +
"element from TreeSet: " + ts);
// first element is removed
System.out.println("First lowest element " +
"removed is : " + ts.pollFirst());
System.out.println("After removing element" +
" from TreeSet: " + ts);
}
}
输出:
Before removing element from TreeSet: [0, 1, 2, 3, 4, 5, 6]
First lowest element removed is : 0
After removing element from TreeSet: [1, 2, 3, 4, 5, 6]
示例 2
// A Java program to demonstrate
// pollFirst() method of TreeSet
import java.util.TreeSet;
public class GFG {
public static void main(String[] args)
{
// creating TreeSet
TreeSet ts = new TreeSet();
// removing element when TreeSet
// is empty
System.out.println("pollFirst() method when " +
"TreeSet is empty : " + ts.pollFirst());
// adding element to the TreeSet
ts.add("Geeks");
ts.add("for");
ts.add("Geek");
// before removing element
System.out.println("Before removing element from" +
" TreeSet: " + ts);
// first element is removed
System.out.println("First lowest element removed is : "
+ ts.pollFirst());
System.out.println("After removing element " +
"from TreeSet: " + ts);
}
}
输出:
pollFirst() method when TreeSet is empty : null
Before removing element from TreeSet: [Geek, Geeks, for]
First lowest element removed is : Geek
After removing element from TreeSet: [Geeks, for]
如果 TreeSet 为空,则此方法返回 null。
示例 3
// A Java program to demonstrate
// pollFirst() method of TreeSet
import java.util.TreeSet;
public class GFG {
public static void main(String[] args)
{
// creating TreeSet
TreeSet ts = new TreeSet();
// before removing element
System.out.println("Before removing " +
"element from TreeSet: " + ts);
// first element is removed
System.out.println("First lowest element " +
"removed is : " + ts.pollFirst());
System.out.println("After removing element" +
" from TreeSet: " + ts);
}
}
输出:
Before removing element from TreeSet: []
First lowest element removed is : null
After removing element from TreeSet: []