Maison  >  Article  >  Java  >  TreeSet en Java

TreeSet en Java

王林
王林original
2024-08-30 15:07:03531parcourir

TreeSet en Java est considéré comme l'une des principales implémentations de l'interface SortedSet qui aide au stockage. En cela, les éléments sont ordonnés de telle manière qu’ils soient placés dans un ordre naturel ou dans un ordre basé sur un comparateur explicite. TreeSet hérite de la classe AbstractSet et implémente l'interface NavigableSet. Même s'il est similaire à HashSet, il conserve un ordre alors que HashSet ne le maintient pas. De plus, les éléments nuls sont autorisés par TreeSet, contrairement à HashSet. Plus de détails sur TreeSet seront abordés dans les sections suivantes.

Commencez votre cours de développement de logiciels libres

Développement Web, langages de programmation, tests de logiciels et autres

Caractéristiques de TreeSet

Vous trouverez ci-dessous les principales fonctionnalités de TreeSet.

  • Les valeurs en double ne sont pas autorisées.
  • Les objets sont triés par ordre croissant.
  • L'ordre d'insertion n'est pas conservé. De plus, les éléments sont triés en fonction des clés.
  • Les objets hétérogènes ne sont pas autorisés à insérer. Si nous essayons d'insérer, classCastException sera levée pendant l'exécution.
  • Stockez une énorme quantité de données triées.
  • Temps de récupération rapide.
  • Accès rapide.
  • Les éléments nuls ne sont pas autorisés.
  • Les opérations telles que l'ajout, la recherche et la suppression prennent le temps de O(log n).
  • Dans le cas d'opérations telles que l'impression d'un nombre n d'éléments, la complexité temporelle de O(n) sera présente.
  • Non synchronisé.
  • La présence de TreeMap est là pour stocker des éléments.
  • Pas thread-safe.

Syntaxe :

Pour créer un TreeSet, importez d'abord le package java.util.TreeSet. Après cela, créez un TreeSet en utilisant la syntaxe :

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

Puisque nous avons créé TreeSet sans mentionner aucun argument, les éléments seront triés dans leur ordre naturel. c'est-à-dire Ordre croissant.

Comme déjà mentionné, le tri peut être personnalisé en utilisant l'interface Comparator.

Constructeurs de TreeSet en Java

TreeSet en Java a 4 constructeurs. Ce sont :

  1. TreeSet() : Un nouveau TreeSet vide sera créé avec un tri basé sur l'ordre naturel.
  2. TreeSet(Collection c) : Un nouveau TreeSet sera créé avec les éléments mentionnés dans la collection c et ils seront triés en fonction de l'ordre naturel.
  3. TreeSet (Comparator comparator) : Un nouveau TreeSet vide sera créé avec un tri basé sur le comparateur mentionné.
  4. TreeSet(SortedSet s) : Un nouveau TreeSet sera créé avec les éléments mentionnés dans les sortedset s avec le même ordre que celui de celui-ci.

Méthodes de TreeSet en Java

Plusieurs fonctions doivent être exécutées dans TreeSet. Voyons ce qu'ils sont.

  • 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 en 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.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn