package demo3;
import java.util.Arrays;
class Student implements Comparable<Student>{
public String name;
public int age;
public Student(String name, int age) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Student o) {
return this.age-o.age;
}
}
public class test {
/* public static void bubble(Comparable[] comparable){
for (int i = 0; i <comparable.length-1 ; i++) {
for (int j = 0; j <comparable.length-1-i ; j++) {
if (comparable[j].compareTo(comparable[j+1])>0){
Comparable tmp=comparable[i];
comparable[j]=comparable[j+1];
comparable[j+1]=tmp;*/
public static void main(String[] args) {
Student[] students=new Student[3];
students[0]=new Student("张三",10);
students[1]=new Student("lisa",5);
students[2]=new Student("王五",15);
Arrays.sort(students);
System.out.println(Arrays.toString(students));
//bubble(students);
System.out.println(Arrays.toString(students));
//System.out.println(student1.compareTo(student2));
}
//引用类型
}
重写compareTo的方法来达到根据年龄来排序,上方定义一个implements接口Comparable
this.age-o.age;通过年龄来排序