62,615
社区成员
发帖
与我相关
我的任务
分享
package com.compare;
import java.util.Arrays;
import java.util.Comparator;
public class Student implements Comparable<Student>{
//就简单点按年龄大小排序
private int age;
Student(){
this.age = 0;
}
Student(int age){
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Student stu) {
if(this.getAge()>stu.getAge()){
return 1;
}else if(this.getAge()<stu.getAge()){
return -1;
}else{
return 0;
}
}
public static void main(String[] args) {
Student stu[] = new Student[3];
stu[0] = new Student(2);
stu[1] = new Student(1);
stu[2] = new Student(3);
// --------方法一----------
Arrays.sort(stu);
// --------方法二----------
Comparator<Student> compare = new Comparator<Student>() {
@Override
public int compare(Student stu1, Student stu2) {
if(stu1.getAge()>stu2.getAge()){
return 1;
}else if(stu1.getAge()<stu2.getAge()){
return -1;
}else{
return 0;
}
}
};
Arrays.sort(stu, compare);
//----------遍历测试-------------
for(Student o:stu){
System.out.println(o.getAge());
}
}
}
Comparator comparator=new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
// TODO Auto-generated method stub
return 0;
}
};