How to Add Custom Class Objects to the TreeSet in Java?


TreeSet is a class of Java Collection Framework that implements the SortedSet Interface. Remember that it stores elements in ascending order and does not allow duplicate values. We need to stick with this condition while adding custom class objects to the TreeSet otherwise we will encounter a ClassCastException. Here, custom class objects mean userdefined objects that are created with the help of a constructor.

Program to add Custom Class Objects to the TreeSet

Earlier in the previous section, we discussed that if we failed to follow the condition of TreeSet, we will get a ClassCastException. To avoid this, we need to implement the Comparable Interface. Let’s discuss this interface quickly

Comparable Interface

This interface is useful when we want to sort custom objects by their natural ordering. For example, It sorts strings in dictionary order and numerics in numerical order. This interface is available in ‘java.lang’ package. Generally, classes and interfaces defined in this package are by default available for our use therefore, it is not necessary to import this package explicitly.

Syntax

class nameOfclass implements Comparable<nameOfclass>

Here, class is the keyword that creates a Class and implements is the keyword that enables the use of features provided by an Interface.

compareTo()

The Comparable interface defines only a single method named ‘CompareTo’ that can be overridden in order to sort the collection of objects. It gives the power to compare the objects of a class to itself. It returns 0 when ‘this’ object is equal to passed object, a positive value if ‘this’ object is greater otherwise a negative value

Syntax

compareTo(nameOfclass nameOfobject);

Approach 1

  • First, import the ‘java.util’ package so that we can work with TreeSet

  • Create a class ‘Cart’ that implements Comparable Interface. Inside it, declare two variables and define a constructor of this class along with two parameters ‘item’ and ‘price’ of type string and integer respectively

  • Define ‘compareTo’ method along with an object of class ‘Cart’ as a parameter to compare ‘this’ object with the newly created object

  • Now, in the main() method, declare an object named ‘trSet’ of class ‘Cart’ of collection type TreeSet and using an in-built method named ‘add()’ store the details of object to the collection.

  • At last, using a for each loop we print the objects of TreeSet.

Example

The following example illustrates how we can add custom class objects to the TreeSet.

import java.util.*;
public class Cart implements Comparable <Cart> {
   String item;
   int price;
   Cart(String item, int price) { // constructor
      // this keyword shows these variables belong to constructor
      this.item = item;
      this.price = price;
   }
   // overriding method
   public int compareTo(Cart comp) {
      if(this.price > comp.price) { // performing comparison
         return 1;
      } else {
         return -1;
      }
   }
   public static void main(String[] args) {
   
      // Declaring collection TreeSet
      TreeSet <Cart> trSet = new TreeSet <Cart>();
      
      // Adding object to the collection
      trSet.add(new Cart("Rice", 59));
      trSet.add(new Cart("Milk", 60));
      trSet.add(new Cart("Bread", 45));
      trSet.add(new Cart("Peanut", 230));
      trSet.add(new Cart("Butter", 55));
      
      // to print the objects
      for (Cart print : trSet) { 
         System.out.println("Item: " + print.item + ", " + "Price: " + print.price);
      }
   }
}

Output

Item: Bread, Price: 45
Item: Butter, Price: 55
Item: Rice, Price: 59
Item: Milk, Price: 60
Item: Peanut, Price: 230

Conclusion

We started this article by introducing the TreeSet class that implements SortedSet Interface. In the next section, we understood Comparable Interface and its built-in method ‘compareTo()’. They are required since the TreeSet collection only accepts comparable objects. At last, we discussed a Java program to add custom class objects to the TreeSet.

Updated on: 20-Jul-2023

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements