构造两个类,一个学生类,包含学号、姓名以及年龄,一个测试类,建立一个学生类的链表,然后按照学号由小到大排序,学号相同(纯属举例使用)按年龄排序。
要利用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;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
}
@Override
public 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;
}
@Override
public 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>(){
@Override
public 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());
}
}
}