📜  Java中的SortedSet接口与示例

📅  最后修改于: 2022-05-13 01:55:26.666000             🧑  作者: Mango

Java中的SortedSet接口与示例

Java.util 包中的 SortedSet 接口扩展了集合框架中的 Set 接口。它是一个实现数学集的接口。该接口包含继承自 Set 接口的方法,并增加了一个特性,该特性将这个接口中的所有元素按排序方式存储。

Set-TreeSet-SortedSet-In-Java-Collection

在上图中,navigable set 扩展了 sorted set 接口。由于集合不保留插入顺序,因此可导航集合接口提供了在集合中导航的实现。实现可导航集的类是 TreeSet,它是自平衡树的实现。因此,这个界面为我们提供了一种在这棵树中导航的方法。

声明: SortedSet 接口声明为:

排序集的示例:

// Java program to demonstrate the
// Sorted Set
import java.util.*;
  
class SortedSetExample{
  
    public static void main(String[] args)
    {
        SortedSet ts
            = new TreeSet();
  
        // Adding elements into the TreeSet
        // using add()
        ts.add("India");
        ts.add("Australia");
        ts.add("South Africa");
  
        // Adding the duplicate
        // element
        ts.add("India");
  
        // Displaying the TreeSet
        System.out.println(ts);
  
        // Removing items from TreeSet
        // using remove()
        ts.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + ts);
  
        // Iterating over Tree set items
        System.out.println("Iterating over set:");
        Iterator i = ts.iterator();
        while (i.hasNext())
            System.out.println(i.next());
    }
}
输出:
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa

注意: SortedSet 的所有元素都必须实现 Comparable 接口(或被指定的 Comparator 接受),并且所有此类元素必须相互可比较。 Mutually Comparable 仅仅意味着两个对象接受彼此作为它们的 compareTo 方法的参数。

创建 SortedSet 对象

由于 SortedSet 是一个接口,因此无法创建 SortedSet 类型的对象。我们总是需要一个扩展这个列表的类来创建一个对象。而且,在Java 1.5 中引入泛型之后,可以限制可以存储在 SortedSet 中的对象类型。这个类型安全的集合可以定义为:

对 SortedSet 执行各种操作

由于 SortedSet 是一个接口,它只能与实现该接口的类一起使用。 TreeSet 是实现 SortedSet 接口的类。现在,让我们看看如何对 TreeSet 执行一些常用的操作。

1. 添加元素:为了向 SortedSet 添加元素,我们可以使用 add() 方法。但是,插入顺序不会保留在 TreeSet 中。在内部,对于每个元素,值都会按升序进行比较和排序。我们需要注意,不允许重复元素,所有重复元素都将被忽略。而且,SortedSet 不接受 Null 值。

// Java code to demonstrate
// the working of SortedSet
import java.util.*;
  
class GFG {
  
    public static void main(String[] args)
    {
        SortedSet ts
            = new TreeSet();
  
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("A");
  
        System.out.println(ts);
    }
}
输出:
[A, B, C]

2. 访问元素:添加元素后,如果我们想访问元素,我们可以使用内置方法,如 contains()、first()、last() 等。

// Java code to demonstrate
// the working of SortedSet
  
import java.util.*;
class GFG {
  
    public static void main(String[] args)
    {
        SortedSet ts
            = new TreeSet();
  
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("A");
  
        System.out.println("Sorted Set is " + ts);
  
        String check = "D";
  
        // Check if the above string exists in
        // the SortedSet or not
        System.out.println("Contains " + check
                           + " " + ts.contains(check));
  
        // Print the first element in
        // the SortedSet
        System.out.println("First Value " + ts.first());
  
        // Print the last element in
        // the SortedSet
        System.out.println("Last Value " + ts.last());
    }
}
输出:
Sorted Set is [A, B, C]
Contains D false
First Value A
Last Value C

3. 删除值:可以使用 remove() 方法从 SortedSet 中删除值。

// Java code to demonstrate
// the working of SortedSet
  
import java.util.*;
class GFG{
  
    public static void main(String[] args)
    {
        SortedSet ts
            = new TreeSet();
  
        // Elements are added using add() method
        ts.add("A");
        ts.add("B");
        ts.add("C");
        ts.add("B");
        ts.add("D");
        ts.add("E");
  
        System.out.println("Initial TreeSet " + ts);
  
        // Removing the element b
        ts.remove("B");
  
        System.out.println("After removing element " + ts);
    }
}
输出:
Initial TreeSet [A, B, C, D, E]
After removing element [A, C, D, E]

4. 遍历SortedSet:有多种方法可以遍历SortedSet。最著名的一种是使用增强的 for 循环。

// Java code to demonstrate
// the working of SortedSet
   
import java.util.*;
class GFG
 { 
    public static void main(String[] args)
    {
        SortedSet ts
            = new TreeSet();
   
        // Elements are added using add() method
        ts.add("C");
        ts.add("D");
        ts.add("E");
        ts.add("A");
        ts.add("B");
        ts.add("Z");
   
        // Iterating though the SortedSet
        for (String value : ts)
            System.out.print(value
                             + ", ");
        System.out.println();
    }
}
输出:
A, B, C, D, E, Z,

实现 SortedSet 接口的类是 TreeSet。

TreeSet:集合框架中实现的TreeSet类是SortedSet接口的实现,SortedSet扩展了Set接口。它的行为类似于一个简单的集合,不同之处在于它以排序格式存储元素。 TreeSet 使用树数据结构进行存储。对象按排序的升序存储。但是我们可以使用 TreeSet.descendingIterator() 方法以降序迭代。让我们看看如何使用这个类创建一个 sortedset 对象。

// Java program to demonstrate the
// creation of SortedSet object using
// the TreeSet class
  
import java.util.*;
  
class GFG {
  
    public static void main(String[] args)
    {
        SortedSet ts
            = new TreeSet();
  
        // Adding elements into the TreeSet
        // using add()
        ts.add("India");
        ts.add("Australia");
        ts.add("South Africa");
  
        // Adding the duplicate
        // element
        ts.add("India");
  
        // Displaying the TreeSet
        System.out.println(ts);
  
        // Removing items from TreeSet
        // using remove()
        ts.remove("Australia");
        System.out.println("Set after removing "
                           + "Australia:" + ts);
  
        // Iterating over Tree set items
        System.out.println("Iterating over set:");
        Iterator i = ts.iterator();
        while (i.hasNext())
            System.out.println(i.next());
    }
}
输出:
[Australia, India, South Africa]
Set after removing Australia:[India, South Africa]
Iterating over set:
India
South Africa

SortedSet 接口的方法

以下是 SortedSet 接口中存在的方法。这里,“*”表示方法是 Set 接口的一部分。

MethodDescription
*add(element)This method is used to add a specific element to the set. The function adds the element only if the specified element is not already present in the set else the function returns False if the element is already present in the Set.
*addAll(collection)This method is used to append all of the elements from the mentioned collection to the existing set. The elements are added randomly without following any specific order.
*clear()This method is used to remove all the elements from the set but not delete the set. The reference for the set still exists.
comparator()This method returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements.
*contains(element)This method is used to check whether a specific element is present in the Set or not.
*containsAll(collection)This method is used to check whether the set contains all the elements present in the given collection or not. This method returns true if the set contains all the elements and returns false if any of the elements are missing.
first()This method returns the first(lowest) element present in this set.
hashCode()This method is used to get the hashCode value for this instance of the Set. It returns an integer value which is the hashCode value for this instance of the Set.
headSet(element)This method returns the elements which are less than the element that are present in the sorted set.
*isEmpty()This method is used to check if a SortedSet is empty or not.
last()This method returns the last(highest) element present in the set.
*remove(element)This method is used to remove the given element from the set. This method returns True if the specified element is present in the Set otherwise it returns False.
*removeAll(collection)This method is used to remove all the elements from the collection which are present in the set. This method returns true if this set changed as a result of the call.
*retainAll(collection)This method is used to retain all the elements from the set which are mentioned in the given collection. This method returns true if this set changed as a result of the call.
*size()This method is used to get the size of the set. This returns an integer value which signifies the number of elements.
subSet(element1, element2)This method returns a sorted subset from the set containing the elements between element1 and element2.
tailSet(element)This method returns the elements which are greater than or equal to the element that are present in the sorted set.
*toArray()This method is used to form an array of the same elements as that of the Set.