62,615
社区成员
发帖
与我相关
我的任务
分享
package com.lin;
public class Student {
private int age;
private int number;
public Student(int age, int number) {
this.age = age;
this.number = number;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
package com.lin;
import java.util.Comparator;
public class ComparatorTest implements Comparator<Student> {
@Override
public int compare(Student o1, Student o2) {
if(o1.getAge() < o2.getAge()){
int num = o1.getAge() - o2.getAge();
// System.out.println(num);
return num;
}else{
int num = o2.getAge() - o1.getAge();
// System.out.println(num);
return num;
}
}
}
package com.lin;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Student s1 = new Student(12,789456);
Student s2 = new Student(13,789455);
Student s3 = new Student(14,789454);
Student s4 = new Student(15,789453);
Student s5 = new Student(16,789452);
list.add(s2);
list.add(s5);
list.add(s3);
list.add(s1);
list.add(s4);
Collections.sort(list, new ComparatorTest());
for(Student s:list){
System.out.println(s.getAge());
}
}
}
public int compare(Student o1, Student o2) {
if(o1.getAge() < o2.getAge()){
int num = o1.getAge() - o2.getAge();
return num;
}else{
int num = o2.getAge() - o1.getAge();
return num;
}
}
按age升序排列直接这样啊。。
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}