Difference Between EnumSet and TreeSet in Java
EnumSet and TreeSet both are the classes defined inside the collection framework. But there are few differences exists between them. In this article, we have tried to cover all these differences between them.
1. EnumSet: EnumSet is a specialized implementation of the Set interface for enumeration types. It extends AbstractSet and implements the Set interface in Java. Few important points of EnumSet are as follows:
- EnumSet class is a member of the Java Collections Framework and it is not synchronized.
- All of the elements in an EnumSet must come from a single enumeration type that is specified when the set is created either explicitly or implicitly.
- EnumSet is much faster than HashSet.
- EnumSet doesn’t allow to insert null object if we try to insert the null object, it will throw NullPointerException.
- It uses a fail-safe iterator, so it won’t throw ConcurrentModificationException if the collection is modified while iterating.
EnumSet : Pink Green
2. TreeSet: TreeSet is a class that implementation the SortedSet interface in Java. It uses the Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. It can also be ordered by a Comparator provided at set creation time, depending on which constructor is used. The TreeSet implements a NavigableSet interface by inheriting AbstractSet class. The class which implements the navigable set is a TreeSet which is an implementation of a self-balancing tree. Therefore, this interface provides us with a way to navigate through this tree.
Tree Set is [For, Geek, Geeks, welcomes, you] Contains : welcomes true First Value For Last Value you Higher Geeks Lower For
Difference between EnumSet and TreeSet:
|Basic||EnumSet is a specialized implementation of the Set interface.||TreeSet is a class that implementation the SortedSet interface in java.|
|Data Structure||It internally represented as a BitVector.||It internally represented as a Red-black tree.|
|Sorting||It sorts the elements according to natural order.||It sorts the elements according to sorted order.|
|Iterator||EnumSet iterator is weakly consistent.||TreeSet iterator is Fail-fast.|
|Best Choice||EnumSet is best choice for storing enumeration type elements.||TreeSet serves as an excellent choice for storing large amounts of sorted information which are supposed to be accessed quickly because of its faster access and retrieval time.|
Please Login to comment...