Java 排序集合接口及其示例
排序集合接口在其名称中包含了“排序”一词,这表示它按升序包含所有元素。它扩展了Set接口的属性。
在本文中,我们将讨论排序集合接口并对其执行一些操作。但是,为了正确理解SortedSet,我们需要了解集合接口的层次结构。
集合接口
在Java中,集合是一个对象,或者我们可以说是一个容器,可以让我们将多个对象分组到一个单元中。集合接口位于所有集合框架接口的根处。我们可以对集合执行添加、删除、遍历、搜索和检索对象等各种操作。请注意,它们不能与int或double等基本数据类型一起使用。不过,Java提供了包装类,可以将基本数据类型用作对象。我们将使用这些对象来操作集合接口。
让我们来讨论集合接口的子接口−
List −它是Java集合接口的子接口。它是一个线性结构,按顺序存储和访问每个元素。
Set −它是Java集合接口的子接口,不允许重复值。它类似于数学集合。
Queue −它提供了队列数据结构的特性。队列遵循先进先出(FIFO)的原则。
SortedSet 接口
正如我们之前讨论的,它按升序存储元素。由于它扩展了Set接口,因此它也不允许重复值,并且可以访问Set接口提供的所有方法。
集合接口位于 ‘java.util’ 包中。要将此包导入到您的程序中,请使用以下命令:
import java.util.*;
这里的‘*’表示我们正在导入此包中所有可用的类。
为了使用SortedSet的特性,我们将使用实现了SortedSet接口的tree set类。
语法
SortedSet< element_Type > collection_name = new TreeSet<>();
在这里, element_Type 是包装类而不是原始数据类型。
除了Set接口的方法之外,它还包括以下方法:
- first() - 返回第一个位置上的对象。
-
last() - 返回最后一个位置上的对象。
-
subSet() - 接受两个参数,并打印出给定参数之间的所有对象。
-
headSet() - 接受一个参数,并返回从开头到指定参数的对象。
-
tailSet() - 接受一个参数,并返回从指定参数到集合末尾的对象。
示例1
在以下示例中,我们将创建一个名为“treeSt”的字符串类型的Tree Set,并使用集合接口的内置方法‘add()’添加一些元素到Tree Set中。它将按照升序打印元素,而不考虑输入元素的顺序。
import java.util.*;
public class Srtset {
public static void main(String args[]) {
// Creating tree set
SortedSet<String> treeSt = new TreeSet<>();
// Adding elements in tree set
treeSt.add("Tutorix");
treeSt.add("Simply");
treeSt.add("Easy");
treeSt.add("Learning");
treeSt.add("Tutorials");
treeSt.add("Point");
System.out.println("Elements of the given set: " + treeSt);
}
}
输出
Elements of the given set: [Easy, Learning, Point, Simply, Tutorials, Tutorix]
示例2
以下示例演示了我们之前在本文中讨论的SortedSet接口的所有内置方法的使用。
import java.util.*;
public class Srtset {
public static void main(String args[]) {
// Creating tree set
SortedSet<String> treeSt = new TreeSet<>();
// Adding elements in tree set
treeSt.add("Tutorix");
treeSt.add("Simply");
treeSt.add("Easy");
treeSt.add("Learning");
treeSt.add("Tutorials");
treeSt.add("Point");
System.out.println("Elements in the given set: " + treeSt);
String frst = treeSt.first();
System.out.println("Accessing First element of the given set: " + frst);
String end = treeSt.last();
System.out.println("Accessing Last element of the given set: " + end);
System.out.println("Accessing subsets of the given set: " + treeSt.subSet("Simply", "Tutorix"));
System.out.println("Accessing first two elements of set: " + treeSt.headSet("Point"));
System.out.println("Accessing last three elements of set: " + treeSt.tailSet("Simply"));
}
}
输出
Elements in the given set: [Easy, Learning, Point, Simply, Tutorials, Tutorix]
Accessing First element of the given set: Easy
Accessing Last element of the given set: Tutorix
Accessing subsets of the given set: [Simply, Tutorials]
Accessing first two elements of set: [Easy, Learning]
Accessing last three elements of set: [Simply, Tutorials, Tutorix]
结论
由于对象存储是按照排序的方式,即升序,所以在SortedSet接口中访问和检索时间变得更快。由于这个出色的特性,SortedSet经常被用来存储需要快速搜索的大量信息。