SortedSet
优质
小牛编辑
113浏览
2023-12-01
SortedSet接口扩展Set并声明按升序排序的集合的行为。 除了由Set定义的那些方法之外,SortedSet接口还声明了下表中汇总的方法 -
当调用集中没有包含任何项时,有几种方法抛出NoSuchElementException。 当对象与集合中的元素不兼容时,抛出ClassCastException。
如果尝试使用null对象并且集合中不允许null,则抛出NullPointerException。
Sr.No. | 方法和描述 |
---|---|
1 | Comparator comparator( ) 返回调用有序集的比较器。 如果自然排序用于此集合,则返回null。 |
2 | Object first( ) 返回调用有序集合中的第一个元素。 |
3 | SortedSet headSet(Object end) 返回一个SortedSet,其中包含调用有序集中包含的小于end的元素。 返回的有序集中的元素也由调用的有序集引用。 |
4 | Object last( ) 返回调用有序集合中的最后一个元素。 |
5 | SortedSet subSet(Object start, Object end) 返回一个SortedSet,其中包含start和end.1之间的元素。 返回集合中的元素也由调用对象引用。 |
6 | SortedSet tailSet(Object start) 返回SortedSet,其中包含排序集中包含的大于或等于start的元素。 返回集中的元素也由调用对象引用。 |
例子 (Example)
SortedSet在TreeSet等各种类中都有实现。 以下是TreeSet类的示例 -
import java.util.*;
public class SortedSetTest {
public static void main(String[] args) {
// Create the sorted set
SortedSet set = new TreeSet();
// Add elements to the set
set.add("b");
set.add("c");
set.add("a");
// Iterating over the elements in the set
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
System.out.println(element.toString());
}
}
}
这将产生以下结果 -
输出 (Output)
a
b
c