本文實(shí)例講述了Java針對(duì)ArrayList自定義排序的2種實(shí)現(xiàn)方法。分享給大家供大家參考,具體如下:
創(chuàng)新互聯(lián)10多年成都企業(yè)網(wǎng)站定制服務(wù);為您提供網(wǎng)站建設(shè),網(wǎng)站制作,網(wǎng)頁(yè)設(shè)計(jì)及高端網(wǎng)站定制服務(wù),成都企業(yè)網(wǎng)站定制及推廣,對(duì)陽臺(tái)護(hù)欄等多個(gè)方面擁有豐富的網(wǎng)站推廣經(jīng)驗(yàn)的網(wǎng)站建設(shè)公司。Java中實(shí)現(xiàn)對(duì)list的自定義排序主要通過兩種方式
1)讓需要進(jìn)行排序的對(duì)象的類實(shí)現(xiàn)Comparable接口,重寫compareTo(T o)方法,在其中定義排序規(guī)則,那么就可以直接調(diào)用Collections.sort()來排序?qū)ο髷?shù)組
public class Student implements Comparable{ private int id; private int age; private int height; private String name; public Student(int id, String name, int age, int height) { this.id = id; this.name = name; this.age = age; this.height = height; } public int getId() { return id; } public int getAge() { return age; } public int getHeight() { return height; } public String getName() { return name; } public void setId(int id) { this.id = id; } public void setAge(int age) { this.age = age; } public void setName(String name) { this.name = name; } public void setHeight(int height) { this.height = height; } @Override public int compareTo(Object o) { Student s = (Student) o; if (this.age > s.age) { return 1; } else if (this.age < s.age) { return -1; } else { if (this.height >= s.height) { return 1; } else { return -1; } } } }