java实现Comparator接口的一个简单示例
看了一圈网上对Comparator接口的实现,感觉都比较复杂,自己实现了一个简单示例供大家参考。
首先实现一个可根据年龄进行比较的【人】类
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
实现Comparator接口
import java.util.Comparator;
public class PersonComparator implements Comparator<Person> {
@Override
public int compare(Person o1, Person o2) {
// if (o1.getAge() > o2.getAge())
// return 1;
// else if (o1.getAge() == o2.getAge())
// return 0;
// return -1;
// 以上代码其实可以用Integer类的compare方法代替
return Integer.compare(o1.getAge(), o2.getAge());
}
}
测试一下根据年龄进行排序
import java.util.Arrays;
public class PersonCompareTest {
public static void main(String[] args) {
Person[] people = {
new Person("张三", 17),
new Person("李四", 20),
new Person("麻子", 18),
};
Arrays.sort(people, new PersonComparator());
for (Person p: people) {
System.out.println(p.toString());
}
}
}
测试结果如下: