java List介面的排序

來源:互聯網
上載者:User

構造兩個類,一個學生類,包含學號、姓名以及年齡,一個測試類別,建立一個學生類的鏈表,然後按照學號由小到大排序,學號相同(純屬舉例使用)按年齡排序。

要利用Collections類中的sort方法,並且需要重寫其中的排序因子,其實就是一個匿名內部類,在這個匿名內部類中寫出需要的定序。

package helloworld;public class Student {String id;String name;int age;public Student(){}public Student(String id, String name, int age){this.id = id;this.name = name;this.age = age;}@Overridepublic String toString() {return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + age;result = prime * result + ((id == null) ? 0 : id.hashCode());result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Student other = (Student) obj;if (age != other.age)return false;if (id == null) {if (other.id != null)return false;} else if (!id.equals(other.id))return false;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}

package helloworld;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.Iterator;import java.util.List;public class StudentTest {public static void main(String[] args) {List<Student> stu = new ArrayList<Student>();Student stu1 = new Student("1000", "aaa", 18);Student stu2 = new Student("1001", "bbb", 19);Student stu3 = new Student("1002", "ccc", 18);Student stu4 = new Student("1001", "ddd", 20);stu.add(stu1);stu.add(stu2);stu.add(stu3);stu.add(stu4);Iterator<Student> it = stu.iterator();while(it.hasNext()){System.out.println(it.next());}Collections.sort(stu, new Comparator<Student>(){@Overridepublic int compare(Student o1, Student o2) {if(o1.id.compareTo(o2.id) == 0){return o1.age-o2.age;}return o1.id.compareTo(o2.id);}});System.out.println("-----------");Iterator<Student> it1 = stu.iterator();while(it1.hasNext()){System.out.println(it1.next());}}}




相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.