1. 程式人生 > 其它 >對 物件的指定屬性就行排序

對 物件的指定屬性就行排序




import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class StudentDeom {
public static void main(String[] args) {
List<Student> list=new ArrayList<Student>();
Student s1 = new Student("張三",20);
Student s2 = new Student("lisu",52);
Student s3 = new Student("awn",60);
Student s4 = new Student("kk",32);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
Collections.sort(list);
System.out.println( list);


}
}




public class Student implements Comparable {

public Student(String name, int age) {

this.name = name;
this.age = age;
}

private String name;
private int age;


public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Student{" +
"age=" + age +
", name='" + name + '\'' +
'}';
}

@Override
public int compareTo(Object o) {
Student student=(Student) o;
return this.getAge()-student.getAge();
}
}