Interfaccia Java SortedSet

In questo tutorial, impareremo a conoscere l'interfaccia SortedSet in Java e i suoi metodi con l'aiuto di un esempio.

L' SortedSetinterfaccia del framework Java Collections viene utilizzata per memorizzare elementi con un certo ordine in un set.

Estende l'interfaccia Set.

Classe che implementa SortedSet

Per poter utilizzare le funzionalità SortedSetdell'interfaccia, dobbiamo utilizzare la TreeSetclasse che la implementa.

Come usare SortedSet?

Per utilizzarlo SortedSet, dobbiamo java.util.SortedSetprima importare il pacchetto.

 // SortedSet implementation by TreeSet class SortedSet animals = new TreeSet(); 

Abbiamo creato un insieme ordinato chiamato animali usando la TreeSetclasse.

Qui non abbiamo usato argomenti per creare un insieme ordinato. Quindi il set verrà ordinato in modo naturale.

Metodi di SortedSet

L' SortedSetinterfaccia include tutti i metodi dell'interfaccia Set. È perché Setè una super interfaccia di SortedSet.

Oltre ai metodi inclusi Setnell'interfaccia, l' SortedSetinterfaccia include anche questi metodi:

  • comparator () : restituisce un comparatore che può essere utilizzato per ordinare gli elementi nell'insieme
  • first () - restituisce il primo elemento del set
  • last () - restituisce l'ultimo elemento del set
  • headSet (element) - restituisce tutti gli elementi del set prima dell'elemento specificato
  • tailSet (element) - restituisce tutti gli elementi del set dopo l'elemento specificato, incluso l'elemento specificato
  • subSet (element1, element2) - restituisce tutti gli elementi tra element1 ed element2 incluso element1

Implementazione di SortedSet nella classe TreeSet

 import java.util.SortedSet; import java.util.TreeSet; class Main ( public static void main(String() args) ( // Creating SortedSet using the TreeSet SortedSet numbers = new TreeSet(); // Insert elements to the set numbers.add(1); numbers.add(2); numbers.add(3); numbers.add(4); System.out.println("SortedSet: " + numbers); // Access the element int firstNumber = numbers.first(); System.out.println("First Number: " + firstNumber); int lastNumber = numbers.last(); System.out.println("Last Number: " + lastNumber); // Remove elements boolean result = numbers.remove(2); System.out.println("Is the number 2 removed? " + result); ) ) 

Produzione

SortedSet: (1, 2, 3, 4) Primo numero: 1 Ultimo numero: 4 Il numero 2 è stato rimosso? vero

Per saperne di più TreeSet, visita Java TreeSet.

Ora che conosciamo l' SortedSetinterfaccia, impareremo la sua implementazione usando la TreeSetclasse.

Articoli interessanti...