Utilizziamo cookie tecnici e di profilazione (anche di terze parti) per migliorare la tua esperienza su questo sito. Continuando la navigazione accetti l'utilizzo dei cookie; in alternativa, leggi l'informativa e scopri come disabilitarli.

Nonostante TreeSet e TreeMap abbiamo molte similitudini, come ad esempio quella di mantenere ordinati gli elementi al loro interno, queste due classi sono molto diverse per altri aspetti, la piu' rilevante delle quali e' che TreeSet e' un Set, cioe' un insieme di elementi senza duplicazioni, TreeMap e' utilizzata per mantenere delle coppie chiave-valore.
In dettaglio le similitudini sono queste: 

  1.  Both TreeMap and TreeSet are Sorted Collection which means they keep there element in predefined Sorted order. Sorting order can be natural sorting order defined by Comparable interface or custom sorting Order defined by Comparator interface. Both TreeMap and TreeSet has overloaded constructor which accept a Comparator, if provided all elements inside TreeSet or TreeMap will be compared and Sorted using this Comparator
  2. TreeSet is practically implemented using TreeMap instance, similarly like HashSet is backed by HashMap instance.
  3. Both TreeSet and TreeMap implements Collection interface so they can be passed to method where a Collection is accepted.
  4. Both TreeMap and TreeSet are non synchronized Collection, hence can not be shared between multiple threads. You can make both TreeSet and TreeMap synchronized by wrapping them into Synchronized collection by callingCollections.synchroinzedMap() method.
  5. Iterator returned by TreeMap and TreeSet are fail-fast, means they will throw ConcurrentModificationException when TreeMap orTreeSet is modified structurally once Iterator is created. this fail-fast behavior is not guaranteed but works in best effort.
  6. Both TreeMap and TreeSet are slower than there Hash counter part like HashSet and HashMap and instead of providing constant time performance for add, remove and get operation they provide performance in O(log(n)) order.
 
Mentre le differenze piu' significative sono: 
  1. TreeSet implements Set interface while TreeMap implements Map interface in Java e quindi non sono ammessi duplicati in TreeSet
  2. TreeSet stores only one object while TreeMap uses two objects called key and Value. Objects in TreeSet are sorted while keys in TreeMap remain in sorted Order.
  3. TreeSet implements NavigableSet while TreeMap implementsNavigableMap in Java.