javaBean實現Comparable介面後排序
阿新 • • 發佈:2019-02-19
今天在做專案時,需要根據序號排序,然而序號是在java中通過邏輯處理賦值的並不是直接在sql中通過order by 解決的;而ArrayList沒有實現Comparable介面,不能實現按需要排序;
<span style="font-family:Microsoft YaHei;">import java.util.ArrayList; import java.util.Collections; import java.util.List; public class StudentSort implements Comparable<Object> { private int id; private String name; public StudentSort(int id,String name) { this.id=id; this.name=name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int compareTo(Object o) { StudentSort student = (StudentSort)o; int id1 = student.getId(); int id2 = this.getId(); return id2>id1?1:-1; } public static void main(String[] args) { StudentSort s1 = new StudentSort(2, "xue"); StudentSort s2 = new StudentSort(1,"yang"); StudentSort s3 = new StudentSort(3,"feng"); List<StudentSort> list = new ArrayList<StudentSort>(); list.add(s3); list.add(s1); list.add(s2); /* 按照id升級排序 * */ Collections.sort(list); for (StudentSort studentSort : list) { System.out.println(studentSort.getId()+":"+studentSort.getName()); } } }</span>