How to Fix java.lang.ClassCastException in TreeSet?
Last Updated : 04 Jan, 2021
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:
- By implementing the Comparable interface
- 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]
Similar Reads
How to fix java.lang.ClassCastException while using the TreeMap in Java? The java.lang.ClassCastException is one of the unchecked exception in Java. It can occur in our program when we tried to convert an object of one class type into an object of another class type. When we use custom class objects as keys in the TreeMap and neither implements the comparable interface n
3 min read
How to Create a TreeSet with a List in Java? TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. TreeSet can be created from List by passing the List to the TreeSet constructor in Java or we can traverse complete List and adding each element of the List to the TreeSet. Example: Input : List = [a, b, c]
3 min read
How to Add Custom Class Objects to the TreeSet in Java? TreeSet is an implementation of the SortedSet interface in java that uses a red-black tree for storage. By default, It maintains an ascending order. It contains unique elements only. It doesn't allow null elements. Access and retrieval times are quite fast. To add the user-defined object into TreeSe
3 min read
Creating and Populating a TreeSet in Java In Java, TreeSet is a pre-defined class that can be used to implement the Set interface and it is a part of the Java collection framework TreeSet is a NavigableSet implementation based on the TreeMap. TreeSet follows the natural order which means elements can be stored in sorted order and it cannot
2 min read
How to sort TreeSet in descending order in Java? Given a TreeSet in Java, task is to sort elements of TreeSet in Descending Order (descreasing order).Examples: Input : Set: [2, 3, 5, 7, 10, 20] Output : Set: [20, 10, 7, 5, 3, 2] Input : Set: [computer, for, geeks, hello] Output : Set: [hello, geeks, for, computer] Approach: To make a TreeSet Eleme
1 min read