TreeSet in Java, TreeSet , TreeSet collection in java


We will cover following points of Treeset in Java:

  1. Basic points about TreeSet in Java.
  2. Adding user define objects in TreeSet.
  3. HashSet vs TreeSet.
  4. Constructors of TreeSet in Java.

Basics of Treeset in Java

  1. TreeSet is a class which extends AbstractSet class(AbstractSet class further implements Set interface) and implements NavigableSet, Cloneable, Serializable interface.
  2. TreeSet store the elements in Sorted order.
  3. If we try to add null as an element in TreeSet, at compile time there is no issue but if we try to iterate the elements at runtime we will get NullPointerException.
  4. We can’t have duplicate elements in TreeSet.
  5. It stores the same types of elements.
  6. We can iterate TreeSet using Iterator and for each loop. We can’t iterate TreeSet elements using ListIterator, Enumeration and normal for loop(as we don’t have get() method in TreeSet like ArrayList).
  7.  None of the TreeSet methods are not synchronized.
  8. TreeSet class internally uses TreeMap.
  9. TreeSet objects are eligible for Serialization and cloning.
  10. It allows null only at index 0 and treeset size should be 1.(As TreeSet perform sort operation adding null will result in NullPointerException.)

Adding user define objects in TreeSet.

If we try to add a user defined class in TreeSet, the class must implement the Comparable interface else we will get ClassCastException.

import java.util.*;
class Book implements Comparable<Book>{

      private String bookName;
      private int id;
      public Book(int id, String bookName) {
             super();
             this.id = id;
             this.bookName = bookName;
      }

      public String getBookName() {
             return bookName;
      }
      public void setBookName(String bookName) {
             this.bookName = bookName;
      }
      public int getId() {
             return id;
      }
      public void setId(int id) {
             this.id = id;
      }

      @Override
      public int compareTo(Book book) {
             int bookId = book.getId();
             return this.id - bookId;
      }
 }

public class Example {
       public static void main(String[] args) {
              Set<Book> setOfBook = new TreeSet<>();
              setOfBook.add(new Book(3,"mahabharta"));
              setOfBook.add(new Book(2,"ramayana"));
              setOfBook.add(new Book(8,"alchemist"));
              setOfBook.add(new Book(4,"godan"));
              setOfBook.add(new Book(1,"panchtantra"));
              for(Book book: setOfBook) {
              System.out.println("book name is "+book.getBookName() +" "+"book id is "+book.getId());
       }

 }
}
Output is –

book name is panchtantra book id is 1
book name is ramayana book id is 2
book name is mahabharta book id is 3
book name is godan book id is 4
book name is alchemist book id is 8

Note – We will get ClassCastException as Book class is not implementing Comparable interface.

Exception in thread “main” java.lang.ClassCastException: addingcustomobjectintreeset.Book cannot be cast to java.lang.Comparable
at java.util.TreeMap.compare(Unknown Source)
at java.util.TreeMap.put(Unknown Source)
at java.util.TreeSet.add(Unknown Source)
at addingcustomobjectintreeset.Example.main(Example.java:38)

HashSet vs TreeSet.

HashSet TreeSet
1. HashSet does not maintain any order. 1. TreeSet maintains ascending order..
2. Hashset allows null value. 2. In case of TreeSet if you add null value it will not give any compile time error but when you will try to iterate the elements it will throw NullPointerException.
3. Hashset is faster than TreeSet. 3. TreeSet is slower than HashSet because it internally perform sorting operation.
4. Hashset internally uses HashMap 4. TreeSet internally uses NavigableMap.
5. If we define generic type Object, in case of HashSet we can have different type of element. 5. In case of TreeSet , we can’t have different type of elements.

Constructor and methods of Treeset in Java

There are four constructors defined for TreeSet.

  • TreeSet()
  • TreeSet(Collection c)
  • TreeSet(Comparator comparator)
  • TreeSet(SortedSet sortedSet)

Learn more about collection in java