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