我正在尝试按其ID排序对象列表。这是我的代码:
List<Employee> employee = getEmployeeList();
Collections.sort(employee, new Comparator<Employee>(){
@Override
public int compare(Employee employee1, Employee employee2) {
return employee1.getEmployeeId().compareTo(employee2.getEmployeeId());
}
});
但排序后没有任何反应,它仍显示原始员工名单。难道我做错了什么?我到处搜索,但他们都只是这样做,它适用于他们。这是一组硬编码的员工ID:
public class Employee{
private String employeeId = "";
private String employeeName = "";
private String contactNbr = "";
//getters and setters
}
List<Employee> empList = new ArrayList<Employee>();
Employee emp1 = new Employee();
emp1.setEmployeeId("A1B1");
empList.add(emp1);
Employee emp2 = new Employee();
emp2.setEmployeeId("A2B1");
empList.add(emp2);
Employee emp3 = new Employee();
emp3.setEmployeeId("A3B1");
empList.add(emp3);
Collections.sort(empList, new Comparator<Employee>(){
@Override
public int compare(Employee employee1, Employee employee2) {
return employee1.getEmployeeId().compareTo(employee2.getEmployeeId());
}
});
答案 0 :(得分:0)
检查employeeId compareTo方法的结果。
如果它总是返回0,则排序将认为所有元素都相等。集合执行稳定的排序,因此如果所有元素都相等,它将保持顺序不变。
答案 1 :(得分:0)
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
public class MainTest {
public static void main(String[] arg)
{
List<Employee> empList = new ArrayList<Employee>();
Employee emp1 = new Employee();
emp1.setEmployeeId("A2B1");
empList.add(emp1);
Employee emp2 = new Employee();
emp2.setEmployeeId("A1B1");
empList.add(emp2);
Employee emp3 = new Employee();
emp3.setEmployeeId("A3B1");
empList.add(emp3);
Collections.sort(empList, new Comparator<Employee>(){
public int compare(Employee employee1, Employee employee2) {
return employee1.getEmployeeId().compareTo(employee2.getEmployeeId());
}
});
Iterator i = empList.iterator();
while(i.hasNext()){
System.out.println(((Employee)i.next()).getEmployeeId());
}
}
}
class Employee{
private String employeeId = "";
private String employeeName = "";
private String contactNbr = "";
public String getContactNbr() {
return contactNbr;
}
public void setContactNbr(String contactNbr) {
this.contactNbr = contactNbr;
}
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
//getters and setters
}
这是正确打印输出: A1B1 A2B1 A3B1
答案 2 :(得分:0)
您要按排序顺序添加列表,这就是您认为列表未获得更新的原因。就您的来源而言,没有任何问题,您正在做正确的事情。问题是你的意见。您按照排序顺序提供以下输入:
emp1.setEmployeeId("A1B1");
empList.add(emp1);
emp1.setEmployeeId("A2B1");
empList.add(emp2);
emp1.setEmployeeId("A3B1");
empList.add(emp3);
您的输出将如下
Before sorting: [A1B1, A2B1, A3B1]
After sorting: [A1B1, A2B1, A3B1]
尝试按如下所示修改来源并检查
emp1.setEmployeeId("A3B1");
empList.add(emp3);
emp1.setEmployeeId("A2B1");
empList.add(emp2);
emp1.setEmployeeId("A1B1");
empList.add(emp1);
您将得到如下结果
Before sorting: [A3B1, A2B1, A1B1]
After sorting: [A1B1, A2B1, A3B1]