Friday, July 26, 2019

TreeSet Vs TreeMap In Java

TreeMap:

All Implemented Interfaces:
Serializable, Cloneable, Map<K,V>, NavigableMap<K,V>, SortedMap<K,V>

public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable

TreeSet:

All Implemented Interfaces:
Serializable, Cloneable, Iterable<E>, Collection<E>, NavigableSet<E>, Set<E>, SortedSet<E>

public class TreeSet<E>
extends AbstractSet<E>
implements NavigableSet<E>, Cloneable, Serializable

Similarities between TreeMap and TreeSet

  • TreeMap and TreeSet both use compareTo() or compare() method to compare object.
  • TreeMap and TreeSet both are sorted data structures. they will store elements in predefined Sorted order.
  • Sorting order will be natural sorting order defined by Comparable or Comparator interface. 
  • TreeMap and TreeSet both has overloaded constructor which accepts a Comparator
  • TreeMap and TreeSet both are non-synchronized.
  • TreeMap and TreeSet both are fail-fast returned by Iterator.
  • TreeMap is slower than hashMap and treeSet is slower than hasSet.
  • Space-complexity wise, both have a complexity of O(n).

Difference between TreeMap and TreeSet

TreeMap TreeSet
TreeMap is an implementation of Map interface. TreeSet is an implementation of the Set interface.
TreeMap is used to store key and values in sorted order TreeSet is used to store value or object in sorted order
TreeMap does allow one duplicate key and any duplicate values. TreeSet also doesn't allow duplicates values
  TreeSet internally uses TreeMap to store objects. Use object to generate Key.
xcscff Time complexity of add, remove, and contains methods is   O(log (n)).
And for first(), last(), headset(), tailset(), etc. time complexity of basic methods is O(1)


Related Tutorials 

No comments:

Post a Comment