Skip to content
Advertisement

I’m getting classcastException , can anybody solve this? [closed]

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)

JavaScript

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.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement