使用可比和比較如下圖所示,您也可以訪問https://www.journaldev.com/780/comparable-and-comparator-in-java-example進一步的細節。
import java.util.Comparator;
class Employee implements Comparable<Employee> {
private int id;
private String name;
private int age;
private long salary;
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public long getSalary() {
return salary;
}
public Employee(int id, String name, int age, int salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public int compareTo(Employee emp) {
//let's sort the employee based on id in ascending order
//returns a negative integer, zero, or a positive integer as this employee id
//is less than, equal to, or greater than the specified object.
return (this.id - emp.id);
}
@Override
//this is required to print the user friendly information about the Employee
public String toString() {
return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
this.salary + "]";
}
}
Default Sorting of Employees list: [[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]
你確實有很多排序算法的,當然實現每個多種語言,你無法找到一個單一使用或改編爲您的使用?這顯示出你明顯缺乏能力或努力,並沒有遵循SO的目標,即回答具體的編碼問題。 – AntonH
你可以實現'Comparable',然後根據你的需要重寫'compareTo'方法,然後調用'Collections.sort(yourArrayList)'方法。這只是其中一種方式... – assembler
[按屬性排序自定義對象的ArrayList]的可能重複(https://stackoverflow.com/questions/2784514/sort-arraylist-of-custom-objects-by-property) –