How to Add Elements to Java TreeSet Example

This example shows how to add elements to TreeSet in Java (including custom class objects). This example also shows how to add elements using the add method and addAll method.

How to add elements to TreeSet in Java using the add method?

The add method of the TreeSet class adds the specified element to the TreeSet object.

The add method adds the specified element to the TreeSet object if it was not already present in the set and returns true. If the element was already present in the set, the set remains unchanged and it returns false.


How to add custom class objects to the TreeSet?

Let’s create a Book custom class and try to add its objects to a TreeSet using the add method.


The code throws “java.lang.ClassCastException: com.javacodeexamples.collections.treeset.Book cannot be cast to java.lang.Comparable” when we run it.

The TreeSet class sorts the elements according to the natural ordering of the elements or by the specified Comparator object. In other words, all the elements of the TreeSet either must implement the Comparable interface or a custom comparator must be provided in the TreeSet constructor.

Let’s implement the Comparable interface in the Book class and try again.


How to add all elements of other collections to the TreeSet using the addAll method?

The addAll method of the TreeSet class adds all the elements of the specified collection to this set.

The addAll method returns true if the set is changed as a result of this method call. The addAll method can be used to convert a collection like HashSet to TreeSet as given below.


This example is a part of the Java TreeSet Tutorial with Examples.

Please let me know your views in the comments section below.

Java 8 TreeSet

About the author



My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping