我试图根据名字缩短员工,但我收到此错误?

时间:2013-07-25 13:22:44

标签: java collections

我在线程“main”java.lang.ClassCastException中收到错误Exception :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)

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



}

2 个答案:

答案 0 :(得分:4)

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

中减去set size()
          //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);

答案 1 :(得分: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()对我来说太低级和冒犯。