Java中的SortedSet first()方法
Java中SortedSet接口的first()方法用于返回第一个,即当前在这个集合中的最低元素。
语法:
E first()
其中,E 是这个 Set 维护的元素的类型。
参数:此函数不接受任何参数。
返回值:它返回当前集合中的第一个或最低的元素。
异常:如果集合为空,则抛出NoSuchElementException 。
下面的程序说明了上述方法:
程序 1 :
Java
// A Java program to demonstrate
// working of SortedSet
import java.util.SortedSet;
import java.util.TreeSet;
public class Main {
public static void main(String[] args)
{
// Create a TreeSet and inserting elements
SortedSet s = new TreeSet<>();
// Adding Element to SortedSet
s.add(1);
s.add(5);
s.add(2);
s.add(3);
s.add(9);
// Returning the lowest element from set
System.out.print("Lowest element in set is : "
+ s.first());
}
}
Java
// Program to illustrate the first()
// method of SortedSet interface
import java.util.SortedSet;
import java.util.TreeSet;
public class GFG {
public static void main(String args[])
{
// Create an empty SortedSet
SortedSet s = new TreeSet<>();
// Trying to access element from
// empty set
try {
s.first();
}
catch (Exception e) {
// throws NoSuchElementException
System.out.println("Exception: " + e);
}
}
}
输出:
Lowest element in set is : 1
方案二:
Java
// Program to illustrate the first()
// method of SortedSet interface
import java.util.SortedSet;
import java.util.TreeSet;
public class GFG {
public static void main(String args[])
{
// Create an empty SortedSet
SortedSet s = new TreeSet<>();
// Trying to access element from
// empty set
try {
s.first();
}
catch (Exception e) {
// throws NoSuchElementException
System.out.println("Exception: " + e);
}
}
}
输出:
Exception: java.util.NoSuchElementException
参考:https: Java/util/SortedSet.html#first()