getting Exception in thread “main” java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader ‘bootstrap’) at java.base/java.lang.String.compareTo(String.java:133) at java.base/java.util.TreeMap.put(TreeMap.java:806) at java.base/java.util.TreeMap.put(TreeMap.java:534) at java.base/java.util.TreeSet.add(TreeSet.java:255) at assignment3treesetdemo.addEmployee(assignment3treesetdemo.java:46) at assignment3treesetdemo.main(assignment3treesetdemo.java:63)
import java.util.Iterator; import java.util.TreeSet; class Employee implements Comparable{ int empid; String name; float salary; Employee(){} Employee(int empid,String name,float salary){ this.empid=empid; this.name=name; this.salary=salary; } @Override public int compareTo(Object o) { Employee emp = (Employee)o; if(salary==emp.salary) return 0; else if(salary>emp.salary) { return 1; } else{ return -1; } } } public class assignment3treesetdemo extends Employee { TreeSet<Object> ts = new TreeSet<>(); assignment3treesetdemo(int empid, String name, float salary) { super(empid, name, salary); } public assignment3treesetdemo() { // TODO Auto-generated constructor stub } boolean addEmployee(Employee emp[]) { int i=0; for(i=0;i<3;i++) { ts.add(emp[i].empid); ts.add(emp[i].name); ts.add(emp[i].salary);} return true; } void displayAllEmployees() { Iterator itr = ts.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } } public static void main(String[] args) { assignment3treesetdemo obj = new assignment3treesetdemo(); Employee emp[] = new Employee[3]; emp[0]=new Employee(101,"Adithya",50); emp[1]=new Employee(102,"Doshk",60); emp[2]=new Employee(103,"Diya",90); obj.addEmployee(emp); obj.displayAllEmployees(); } }
Advertisement
Answer
You’re putting an int
(boxed to Integer
), a float
(boxed to Float
) and a String
in the same TreeMap
. Because you didn’t specify a Comparator
when you created the TreeMap
, the compareTo
methods of these separate objects are called. These compareTo
methods are allowed to (and will) throw a ClassCastException
if the object passed to it isn’t of the same type. That’s what you’re seeing here.
As said before, you probably just want to add the employee itself. That way, the compareTo
method of your Employee
class will called and not the compareTo
method of Integer
, Float
or `String.