Heim  >  Artikel  >  Java  >  TreeSet in Java

TreeSet in Java

王林
王林Original
2024-08-30 15:07:03531Durchsuche

TreeSet in Java gilt als eine der Hauptimplementierungen der Schnittstelle SortedSet, die bei der Speicherung hilft. Dabei werden Elemente so geordnet, dass sie in eine natürliche oder auf einem expliziten Komparator basierende Reihenfolge gesetzt werden. TreeSet erbt die Klasse AbstractSet und implementiert die Schnittstelle NavigableSet. Obwohl es HashSet ähnelt, behält es eine Reihenfolge bei, während HashSet diese nicht beibehält. Darüber hinaus sind bei TreeSet im Gegensatz zu HashSet Nullelemente zulässig. Weitere Details zu TreeSet werden in den folgenden Abschnitten besprochen.

Starten Sie Ihren kostenlosen Softwareentwicklungskurs

Webentwicklung, Programmiersprachen, Softwaretests und andere

Funktionen von TreeSet

Im Folgenden sind die Hauptfunktionen von TreeSet aufgeführt.

  • Doppelte Werte sind nicht zulässig.
  • Objekte werden in aufsteigender Reihenfolge sortiert.
  • Die Einfügungsreihenfolge wird nicht beibehalten. Darüber hinaus werden Elemente nach Schlüsseln sortiert.
  • Heterogene Objekte dürfen nicht eingefügt werden. Wenn wir versuchen, etwas einzufügen, wird zur Laufzeit eine classCastException ausgelöst.
  • Speichern Sie eine große Menge sortierter Daten.
  • Schnelle Abrufzeit.
  • Schnellzugriff.
  • Null-Elemente sind nicht zulässig.
  • Vorgänge wie Hinzufügen, Suchen und Entfernen benötigen die Zeit von O(log n).
  • Bei Operationen wie dem Drucken einer Anzahl von n Elementen ist die zeitliche Komplexität von O(n) vorhanden.
  • Nicht synchronisiert.
  • Das Vorhandensein von TreeMap dient zum Speichern von Elementen.
  • Nicht Thread-sicher.

Syntax:

Um ein TreeSet zu erstellen, importieren Sie zunächst das Paket java.util.TreeSet. Erstellen Sie anschließend ein TreeSet mit der Syntax:

TreeSet<Integer> num= new TreeSet<>();

Da wir TreeSet erstellt haben, ohne irgendwelche Argumente zu erwähnen, werden die Elemente in ihrer natürlichen Reihenfolge sortiert. d.h. Aufsteigende Reihenfolge.

Wie bereits erwähnt, kann die Sortierung mithilfe der Schnittstelle Comparator angepasst werden.

Konstruktoren von TreeSet in Java

TreeSet in Java hat 4 Konstruktoren. Sie sind:

  1. TreeSet(): Ein neues und leeres TreeSet wird mit Sortierung basierend auf der natürlichen Reihenfolge erstellt.
  2. TreeSet(Collection c): Ein neues TreeSet wird mit den in der Sammlung c genannten Elementen erstellt und diese werden basierend auf der natürlichen Reihenfolge sortiert.
  3. TreeSet(Comparator comparator): Ein neues und leeres TreeSet wird mit Sortierung basierend auf dem genannten Komparator erstellt.
  4. TreeSet(SortedSet s): Ein neues TreeSet wird mit den in den sortedset s genannten Elementen erstellt, wobei die Reihenfolge mit der darin identischen Reihenfolge übereinstimmt.

Methoden von TreeSet in Java

Es gibt mehrere Funktionen, die in TreeSet ausgeführt werden müssen. Lasst uns sehen, was sie sind.

  • add(Ee): An element e will be added to the set if it is not present in it.
  • addAll(CollectionE> c): All the elements in collection c will be added to the set.
  • E ceiling(Ee): The last element which is greater than or equal to the element in the set will be returned.
  • clear(): All the elements in the set will be removed.
  • clone(): A shallow copy will be returned for the TreeSet instance.
  • comparator(): The comparator used in the set will be returned. If natural ordering is used, null will be returned.
  • contains(Objecto): If the set contains the element o, true will be returned.
  • descendingIterator(): An iterator will be returned over the elements in descending order.
  • descendingSet(): A reverse order view will be returned for the elements present in the list.
  • first(): he first or the lowest element in the set will be returned.
  • last(): The last or the largest element in the set will be returned.
  • iterator(): n iterator will be returned over the elements in ascending order.
  • lower(Ee): The greatest element will be returned which is strictly small than the element e which is given. If there is no such element, null will be returned.
  • higher(Ee): The smallest element will be returned which is strictly high than the element e which is given. If there is no such element, null will be returned.
  • isEmpty(): True will be returned if no elements are present.
  • size(): The number of elements in the set will be returned. In other words, cardinality will be returned.
  • pollFirst(): The first or the lowest element in the set will be retrieved and removed. If there are no elements in the set, the null will be returned.
  • pollLast(): The last or the highest element in the set will be retrieved and removed. If there are no elements in the set, the null will be returned.
  • remove(Objecto): If the set contains the element o, it will be removed.
  • subSet(EfromElement, boolean fromInclusive, E toElement, boolean toInclusive): A view will be returned for the portion of the set from the range from Element to toElement.
  • subSet(EfromElement, E toElement): A view will be returned for the portion of the set from the range fromElement(inclusive) to toElement(exclusive).
  • tailSet(EfromElement):  view will be returned for the portion of the set where elements are larger than fromElement.
  • tailSet(EfromElement, boolean inclusive): A view will be returned for the portion of the set where elements are larger than fromElement. It is considered if inclusive is true.

Example of TreeSet in Java

Java program to create a tree set with the natural ordering of elements.

import java.util.SortedSet;
import java.util.TreeSet;
//class
public class TreeSetExample {
//main method
public static void main(String[] args) {
//  TreeSet <u>fam</u> creation
SortedSet<String> fam = new TreeSet<>();
// Adding new elements to a TreeSet
fam.add("Anna");
fam.add("Adam");
fam.add("Sam");
fam.add("Iza");
//print the treeset
System.out.println("Fam Set : " + fam);
// Trying to add duplicate element <u>Anna</u>
fam.add("Anna");
System.out.println("Added element Anna, Now the treeset is : " + fam);
// Trying to add  element <u>Anna</u> with lower case
fam.add("anna");
System.out.println("Added element anna, Now the treeset is  : " + fam);
}
}

Output:

TreeSet in Java

A treeset fam is created first. Once it is created, elements are added to it and the whole treeset is printed. After this, an element ‘Anna’ which is already present in the treeset is trying to get added. Since duplicates are not allowed in TreeSet, it is not get added. After that, an element ‘anna’ which is the lower case of the already existing element ‘Anna’ is added. Since it is in lowercase, it gets added to the treeset without any problem.

Conclusion

TreeSet in Java is an implementation of the interface SortedSet that helps in storage where the elements are arranged in natural ordering or based on the comparator. Several aspects of TreeSet is discussed in this document.

Das obige ist der detaillierte Inhalt vonTreeSet in Java. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:Was sind JavaBeans?Nächster Artikel:Was sind JavaBeans?