使用下面的代码。但它以对象形式而不是字符串形式给出响应。让我知道我错在哪里...
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Employee5 {
String name;
public String getName() {
// TODO Auto-generated method stub
return name.toString();
}
void setName(String nameOfEmp) {
name = nameOfEmp;
}
}
class EmpSortByName implements Comparator<Employee5> {
public int compare(Employee5 o1, Employee5 o2) {
return o1.getName().compareTo(o2.getName());
}
}
public class ComparatorExampleInJava {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
Employee5 emp1 = new Employee5();
emp1.setName("A");
Employee5 emp2 = new Employee5();
emp2.setName("C");
Employee5 emp3 = new Employee5();
emp3.setName("B");
List lst = new ArrayList();
lst.add(emp1);
lst.add(emp2);
lst.add(emp3);
System.out.println("Before Sort : " + lst);
try {
Collections.sort(lst, new EmpSortByName());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("After Sort : " + lst);
}
}
获取输出:排序前:[Employee5@19821f,Employee5@addbf1,Employee5@42e816] 排序后:[Employee5@19821f,Employee5@42e816,Employee5@addbf1]
期望的输出:排序前:[A,C,B] 排序后:[A,B,C]