Skip to content
Related Articles

Related Articles

How to Fix java.lang.ClassCastException in TreeSet?
  • Last Updated : 04 Jan, 2021
GeeksforGeeks - Summer Carnival Banner

TreeSet class in Java implements the Set interface that uses a tree for storing elements which contain unique objects stored in the ascending order. You may come across an exception called java.lang.ClassCastException while working with TreeSet objects. Basically, TreeSet elements are ordered using natural ordering or by using the Comparator defined in the constructor. If both don’t happen i.e natural ordering not occurring and also did not provide any comparator then java throws an exception which is java.lang.ClassCastException.

Example

Java




// Java program to demonstrate ClassCastException by TreeSet
  
import java.util.TreeSet;
  
// class which is going to assign
// student marks
class Student {
  
    int marks;
  
    // constructor
    public Student(int marks) { this.marks = marks; }
  
    // override toString() method
    // for display purpose
    public String toString()
    {
        return "Student marks = " + this.marks;
    }
}
  
// Driver class
class GFG {
    public static void main(String[] args)
    {
  
        // Declaring Tree Set
        TreeSet<Student> treeSet = new TreeSet<Student>();
  
        // this line will throw java.lang.ClassCastException
        treeSet.add(new Student(1));
  
        // Displaying the contents of in treeSet
        System.out.println(treeSet);
    }
}

Output

Exception in thread “main” java.lang.ClassCastException: class Student cannot be cast to class java.lang.Comparable (Student is in unnamed module of loader ‘app’; java.lang.Comparable is in module java.base of loader ‘bootstrap’)



at java.base/java.util.TreeMap.compare(TreeMap.java:1291)

at java.base/java.util.TreeMap.put(TreeMap.java:536)

at java.base/java.util.TreeSet.add(TreeSet.java:255)

at GFG.main(File.java:31)

We can resolve this exception in two ways:

  1. By implementing the Comparable interface
  2. By defining custom Comparator class

Approach 1(Implementing Comparable Interface)

Java Comparable interface is implemented by a class by which used to compare and sort the objects according to the natural ordering. Natural ordering is possible using compareTo() function. String objects and wrapper class objects are sorted according to the built-in compareTo() function.

If compareTo function returns positive or negative or zero, then the current object is greater, lesser, and equal to the provided object respectively.

Example 1:  

Java




// Java program to sort student data
// according to marks
// using Comparable interface
  
import java.util.TreeSet;
  
// class which is going to assign
// student marks
class Student implements Comparable<Student> {
  
    int id;
    String name;
    int marks;
  
    // constructor
    public Student(int id, String name, int marks)
    {
  
        // assigning values
        this.id = id;
        this.name = name;
        this.marks = marks;
    }
  
    // compareTo method to sort in
    // ascending order
    public int compareTo(Student obj)
    {
        return this.marks - obj.marks;
    }
  
    // override toString() method
    // for display purpose
    public String toString()
    {
        return "Id: " + this.id + " Name: " + this.name
            + " Marks: " + this.marks;
    }
}
  
// Driver class
class GFG {
    public static void main(String[] args)
    {
  
        // Declaring Tree Set
        TreeSet<Student> treeSet = new TreeSet<Student>();
  
        treeSet.add(new Student(1, "Suresh", 87));
        treeSet.add(new Student(2, "Ramesh", 78));
        treeSet.add(new Student(3, "Lokesh", 95));
  
        // Displaying the contents of in treeSet
        System.out.println(treeSet);
    }
}
Output
[Id: 2 Name: Ramesh Marks: 78, Id: 1 Name: Suresh Marks: 87, Id: 3 Name: Lokesh Marks: 95]

 Approach 2(Using Custom Comparator class)

A comparator is an interface that has to implemented by the class by which we can sort the objects of the user-defined class. It has 2 main methods that are used widely, compare(T o1, T o2) and equals(Object obj) which returns an int and boolean respectively. Let us implement the same example using a comparator.

Java




// Java program to sort student data
// according to marks using custom class
// which implements Comparator
  
// comparator interface present in
// java.util package
import java.util.*;
// class which is going to assign
// student marks
class Student {
  
    int id;
    String name;
    int marks;
  
    // constructor
    public Student(int id, String name, int marks)
    {
  
        // assigning values
        this.id = id;
        this.name = name;
        this.marks = marks;
    }
  
    // method to return
    // current marks of student
    public int getMarks() { return this.marks; }
  
    // override toString() method
    // for display purpose
    public String toString()
    {
        return "Id: " + this.id + " Name: " + this.name
            + " Marks: " + this.marks;
    }
}
  
// StuComparator class will compare
// objects ans sorts in
// ascending order
class StuComparator implements Comparator<Student> {
  
    // defining compare method
    public int compare(Student obj1, Student obj2)
    {
        return obj1.getMarks() - obj2.getMarks();
    }
}
  
// Driver class
class GFG {
    public static void main(String[] args)
    {
  
        // Declaring Tree Set
        TreeSet<Student> treeSet
            = new TreeSet<Student>(new StuComparator());
  
        treeSet.add(new Student(1, "Suresh", 87));
        treeSet.add(new Student(2, "Ramesh", 78));
        treeSet.add(new Student(3, "Lokesh", 95));
  
        // Displaying the contents of in treeSet
        System.out.println(treeSet);
    }
}
Output
[Id: 2 Name: Ramesh Marks: 78, Id: 1 Name: Suresh Marks: 87, Id: 3 Name: Lokesh Marks: 95]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :