我得到 classcastException ,任何人都可以解决这个问题吗?

I'm getting classcastException , can anybody solve this?

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();
    
    
}
}

您将一个 int(装箱到 Integer)、一个 float(装箱到 Float)和一个 String 放在同一个位置TreeMap。因为在创建 TreeMap 时没有指定 Comparator,所以会调用这些单独对象的 compareTo 方法。如果传递给它的对象不是同一类型,则允许这些 compareTo 方法(并将)抛出 ClassCastException。这就是您在这里看到的。

如前所述,您可能只想添加员工本身。这样,将调用 Employee class 的 compareTo 方法,而不是 IntegerFloat 或 `String.[ 的 compareTo 方法。 =26=]