标签:add ons imp pareto ati vat tor 自动调用 method
继承Comparable接口,重写compareTo方法进行排序:
public class Student implements Comparable<Student>{
private String name;
private int id;
private int age;
public Student() {
super();
}
public Student(String name, int id, int age) {
super();
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", id=" + id + ", age=" + age + "]";
}
@Override
public int compareTo(Student s) {
return this.age-s.age;
}
}
public class Test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Student> list = new ArrayList<Student>();
Student s1 = new Student("张三",1,16);
Student s2 = new Student("张四",2,12);
Student s3 = new Student("张五",3,18);
list.add(s1);list.add(s2);list.add(s3);
//Collections.sort()会自动调用compareTo()方法
Collections.sort(list);
for (Student student : list) {
System.out.println(student);
}
}
}
运行:
Student [name=张四, id=2, age=12]
Student [name=张三, id=1, age=16]
Student [name=张五, id=3, age=18]
Comparetor下的compare方法排序:
public class Student{
private String name;
private int id;
private int age;
public Student() {
super();
}
public Student(String name, int id, int age) {
super();
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", id=" + id + ", age=" + age + "]";
}
}
public class Test01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Student> list = new ArrayList<Student>();
Student s1 = new Student("张三",1,16);
Student s2 = new Student("张四",2,12);
Student s3 = new Student("张五",3,18);
list.add(s1);list.add(s2);list.add(s3);
Collections.sort(list, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
// TODO Auto-generated method stub
return o1.getAge()-o2.getAge();
}
});
for (Student student : list) {
System.out.println(student);
}
}
}
运行:
Student [name=张四, id=2, age=12]
Student [name=张三, id=1, age=16]
Student [name=张五, id=3, age=18]
Collections接口下的Comparetor类和Comparable接口排序
标签:add ons imp pareto ati vat tor 自动调用 method
原文地址:https://www.cnblogs.com/snzd9958/p/9792649.html