0

我在线程“main”java.lang.ClassCastException 中收到错误异常:com.genous.Employee 无法转换为 java.lang.Comparable

在 java.util.Arrays.mergeSort(Arrays.java:1157)

在 java.util.Arrays.sort(Arrays.java:1092)

在 java.util.Collections.sort(Collections.java:134)

在 com.genious.Employee.main(Employee.java:54)//

public class Employee implements Comparator
{
String firstname;
String lastname;
int mobileno;
public Employee(String firstname,String lastname,int mobileno)
{
this.firstname=firstname;
this.lastname=lastname;
this.mobileno=mobileno;
}

@Override
public String toString() {
        return firstname;
}


@Override
public int compare(Object o1, Object o2) {
Employee e2=(Employee)o1;
Employee e3=(Employee)o2;
int i=e2.firstname.compareTo(e3.firstname);
if(i!=0)
    return i;

return i;
}


/**
 * @param args
 */
public static void main(String[] args) {
ArrayList list=new ArrayList();
    Employee e=new Employee("anand","pandey",93456666);
    Employee e1=new Employee("sheel","nidhi",678956344);
    Employee e5=new Employee("shumit", "Kumar", 97390267);
    Employee e6=new Employee("Kamal", "Kumar", 97390267);
    list.add(e);
    list.add(e1);
    list.add(e5);
    list.add(e6);
    System.out.println(list);
Collections.sort(list);
    System.out.println(list);
}



}
4

2 回答 2

4

您可以覆盖equals()员工类中的方法并将所有员工对象添加到集合而不是列表中,您将获得唯一员工对象的列表。如果您想要重复条目的计数,您可以从列表大小中减去集合大小() ()

          //Provided you have overriden the equals() method
          List<Employee> employeeList = new ArrayList<Employee>();
          Set<Employee> employeeSet = new HashSet<Employee>(employeeList);

          int dupEntries = employeeList.size() - employeeSet.size();
          System.out.println("Dup Entries : "+dupEntries);
于 2013-07-25T13:27:59.903 回答
3

实现 Comparable 接口

public class Empl implemnents Comparable{
  public int compareTo(Empl  o){
    if(.... your check if duplicate ....) 
      return 0;
    return -1;
  };
}

试试这个

ArrayList<Empl> yourlist = ...;
TreeSet ts = new TreeSet();
ts.addAll(yourlist);
yourlist.removeAll(ts);

现在你的列表有所有重复项。覆盖equals()对我来说太低级和冒犯。

于 2013-07-25T13:28:43.717 回答