使用下面的一段代碼。但它是以對象形式給出響應而不是String。讓我知道我錯了......比較器 - 沒有得到預期的結果
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]