Why does TreeSet throw a ClassCastException?

前端 未结 6 820
遥遥无期
遥遥无期 2020-11-29 06:30

I am trying to add two \'Employee\' objects to a TreeSet:

Set s = new TreeSet();
s.add(new Employee(1001));
s.add(new Employe         


        
6条回答
  •  孤独总比滥情好
    2020-11-29 07:18

    //class Employee
        public class Employee implements Comparable{
        int id;
    
        Employee(int id){
        this.id=id;
        }
    
        public int compareTo(Employee e){ //implementing abstract method.
        if(id>e.id){
        return 1;
        }
        return 0;
        }
    
    
    //class TreeSet
    
        Set emp =new TreeSet();
    
        Employee eobj1 = new Employee(2);
        Employee eobj2 = new Employee(3);
        emp.add(eobj1);
        emp.add(eobj2);
    
        for (Student ss:emp) {
        System.out.println(ss.rollno);
        }
    }
    //output: 2
    //        3
    

提交回复
热议问题