Open In App

How to Fix java.lang.ClassCastException in TreeSet By Using Custom Comparator in Java?

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

This error is thrown by TreeSet because TreeSet is used to store elements in sorted order and if the specified element cannot be compared with the elements currently in the set then TreeSet won’t be able to store elements in sorted order and hence, TreeSet throws class cast exception.

How to fix this error?

  • By providing a custom Comparator in TreeSet constructor.

In wrapper class like Integer, Double, etc Comparator interface is already implemented, so we don’t need to worry. But whenever we use a user-defined class in TreeSet we have to do either of the above-mentioned ways.

Approach: By providing a custom Comparator in TreeSet constructor

Unlike Comparable, Comparator is external to the element type we are comparing. It’s a separate class. We create multiple separate classes (that implement Comparator) to compare by different members.

  • Create a class that implements Comparator (and thus the compare() method that does the work previously done by compareTo()).
  • Make an instance of the Comparator class.
  • Call the overloaded sort() method, giving it both the list and the instance of the class that implements Comparator.

Java




// Java program to fix java.lang.ClassCastException
// in TreeSet using Comparator
  
import java.util.Comparator;
import java.util.TreeSet;
  
class friendsMarks {
    // class field
    String name;
    String nickName;
    int marks;
  
    // parameterised constructor
    public friendsMarks(String name, String nickName,
                        int marks)
    {
        this.name = name;
        this.nickName = nickName;
        this.marks = marks;
    }
  
    // getter for name
    public String getName() { return name; }
  
    // setter for name
    public void setName(String name) { this.name = name; }
  
    // getter for marks
    public int getMarks() { return marks; }
  
    // setter for marks
    public void setMarks(int marks) { this.marks = marks; }
  
    // getter for nickname
    public String getNickName() { return nickName; }
  
    // setter for nickname
    public void setNickName(String nickName)
    {
        this.nickName = nickName;
    }
  
    //@Override toString method
    public String toString()
    {
        return "friendsMarks{"
            + "name='" + name + '\'' + ", nickName='"
            + nickName + '\'' + ", marks=" + marks + '}';
    }
}
  
// for comparing names
class nameCompare implements Comparator<friendsMarks> {
  
    @Override
    public int compare(friendsMarks friend1,
                       friendsMarks friend2)
    {
        return friend1.getName().compareTo(
            friend2.getName());
    }
}
  
// for comparing marks
class marksCompare implements Comparator<friendsMarks> {
  
    @Override
    public int compare(friendsMarks f1, friendsMarks f2)
    {
        if (f1.getMarks() > f2.getMarks()) {
            return 1;
        }
        else {
            return -1;
        }
    }
}
  
// for comparing nick name
class nickNameCompare implements Comparator<friendsMarks> {
  
    @Override
    public int compare(friendsMarks obj1, friendsMarks obj2)
    {
        return obj1.getNickName().compareTo(
            obj2.getNickName());
    }
}
public class Main {
  
    public static void main(String[] args)
    {
  
        // Creating TreeSet
        // and we have to pass Comparator object
        // of marksCompare class
        // in the TreeSet constructor
        // so that we can sort according to the marks
        TreeSet<friendsMarks> treeSet
            = new TreeSet<>(new marksCompare());
  
        // adding elements to TreeSet
        treeSet.add(new friendsMarks("Raushan", "Chamgader", 99));
        treeSet.add(new friendsMarks("Yashdeep", "Dopa", 95));
        treeSet.add(new friendsMarks("Rupesh", "Gian", 92));
        treeSet.add(new friendsMarks("Shivam", "Gorilla", 47));
        treeSet.add(new friendsMarks("Sarthak", "Nagin", 78));
        treeSet.add(new friendsMarks("Sonika", "Chipkali", 67));
        treeSet.add(new friendsMarks("Himanshu", "Lalten", 57));
  
        System.out.println("Sorting on the basis of marks");
  
        // Displaying using loop
        for (friendsMarks tree : treeSet)
            System.out.println(tree);
  
        // Creating TreeSet
        // and we have to pass Comparator object
        // of nameCompare class
        // in the TreeSet constructor
        // so that we can sort according to the name
        TreeSet<friendsMarks> treeSet1
            = new TreeSet<>(new nameCompare());
  
        // adding elements to TreeSet
        treeSet1.add(new friendsMarks("Raushan", "Chamgader", 99));
        treeSet1.add(new friendsMarks("Yashdeep", "Dopa", 95));
        treeSet1.add(new friendsMarks("Rupesh", "Gian", 92));
        treeSet1.add(new friendsMarks("Shivam", "Gorilla", 47));
        treeSet1.add(new friendsMarks("Sarthak", "Nagin", 78));
        treeSet1.add(new friendsMarks("Sonika", "Chipkali", 67));
        treeSet1.add(new friendsMarks("Himanshu", "Lalten", 57));
  
        // Displaying using loop
        System.out.println("\n\nSorting on the basis of name");
  
        for (friendsMarks tree : treeSet1)
            System.out.println(tree);
  
        // Creating TreeSet
        // and we have to pass Comparator object
        // of nickNameCompare class
        // in the TreeSet constructor
        // so that we can sort according to the nickname
        TreeSet<friendsMarks> treeSet2
            = new TreeSet<>(new nickNameCompare());
  
        // adding elements to TreeSet
        treeSet2.add(new friendsMarks("Raushan", "Chamgader", 99));
        treeSet2.add(new friendsMarks("Yashdeep", "Dopa", 95));
        treeSet2.add(new friendsMarks("Rupesh", "Gian", 92));
        treeSet2.add(new friendsMarks("Shivam", "Gorilla", 47));
        treeSet2.add(new friendsMarks("Sarthak", "Nagin", 78));
        treeSet2.add(new friendsMarks("Sonika", "Chipkali", 67));
        treeSet2.add(new friendsMarks("Himanshu", "Lalten", 57));
  
        // Displaying using loop
        System.out.println("\n\nSorting on the basis of nick-name");
  
        for (friendsMarks tree : treeSet2)
            System.out.println(tree);
    }
}


Output

Sorting on the basis of marks
friendsMarks{name='Shivam', nickName='Gorilla', marks=47}
friendsMarks{name='Himanshu', nickName='Lalten', marks=57}
friendsMarks{name='Sonika', nickName='Chipkali', marks=67}
friendsMarks{name='Sarthak', nickName='Nagin', marks=78}
friendsMarks{name='Rupesh', nickName='Gian', marks=92}
friendsMarks{name='Yashdeep', nickName='Dopa', marks=95}
friendsMarks{name='Raushan', nickName='Chamgader', marks=99}


Sorting on the basis of name
friendsMarks{name='Himanshu', nickName='Lalten', marks=57}
friendsMarks{name='Raushan', nickName='Chamgader', marks=99}
friendsMarks{name='Rupesh', nickName='Gian', marks=92}
friendsMarks{name='Sarthak', nickName='Nagin', marks=78}
friendsMarks{name='Shivam', nickName='Gorilla', marks=47}
friendsMarks{name='Sonika', nickName='Chipkali', marks=67}
friendsMarks{name='Yashdeep', nickName='Dopa', marks=95}


Sorting on the basis of nick-name
friendsMarks{name='Raushan', nickName='Chamgader', marks=99}
friendsMarks{name='Sonika', nickName='Chipkali', marks=67}
friendsMarks{name='Yashdeep', nickName='Dopa', marks=95}
friendsMarks{name='Rupesh', nickName='Gian', marks=92}
friendsMarks{name='Shivam', nickName='Gorilla', marks=47}
friendsMarks{name='Himanshu', nickName='Lalten', marks=57}
friendsMarks{name='Sarthak', nickName='Nagin', marks=78}


Last Updated : 07 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads