Java 集合框架
SortedSet是集合框架中的接口。此接口扩展了Set并提供其元素的总排序。实现此接口的Exampled类是TreeSet。
SortedSet的所有元素都必须实现Comparable接口(或者被指定的Comparator接受),并且所有这些元素必须是可相互比较的(即,Mutual Comparable只是意味着两个对象互相接受作为compareTo方法的参数)
SortedSet接口的方法:
comparator():返回用于对此集合中的元素进行排序的比较器,如果此集合使用其元素的自然顺序,则返回null。
first():返回此集合中当前的第一个(最低)元素。
headSet(E toElement):返回此set的部分视图,其元素严格小于toElement。
last():返回此集合中当前的最后一个(最高)元素。
subSet(E fromElement,E toElement):返回此set的部分视图,其元素范围从fromElement(包括)到toElement(不包括)。
tailSet(E fromElement):返回此set的部分元素,其元素大于或等于fromElement。
public interface SortedSet extends Set
{
// Range views
SortedSet subSet(E fromElement, E toElement);
SortedSet headSet(E toElement);
SortedSet tailSet(E fromElement);
// Endpoints
E first();
E last();
// Comparator access
Comparator comparator();
}
// 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 sites = new TreeSet<>();
sites.add("practice");
sites.add("geeksforgeeks");
sites.add("quiz");
sites.add("code");
System.out.println("Sorted Set: " + sites);
System.out.println("First: " + sites.first());
System.out.println("Last: " + sites.last());
// Getting elements before quiz (Excluding) in a sortedSet
SortedSet beforeQuiz = sites.headSet("quiz");
System.out.println(beforeQuiz);
// Getting elements between code (Including) and
// practice (Excluding)
SortedSet betweenCodeAndQuiz =
sites.subSet("code","practice");
System.out.println(betweenCodeAndQuiz);
// Getting elements after code (Including)
SortedSet afterCode = sites.tailSet("code");
System.out.println(afterCode);
}
}
输出:
Sorted Set:
First: code
Last: quiz