Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Fix java.lang.ClassCastException in TreeSet?
Next article icon

How to Fix java.lang.ClassCastException in TreeSet?

Last Updated : 04 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

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]

Next Article
How to Fix java.lang.ClassCastException in TreeSet?

D

dadimadhav
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Java Programs
  • Technical Scripter 2020
  • java-treeset
Practice Tags :
  • Java

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences