Java中的排序和比较中经常用到Comparable和Comparator这两个接口,这两个接口都可以重写该比较方法,实现除了基本数据类型外的实体类的字段比较和排序,这里讲三个方法扩展接口的应用。
[Comparable扩展类]:
class StuComparable implements Comparable<StuComparable> {
private int age;
private String name;
/**
* @param age
* @param name
*/
public StuComparable(int age, String name) {
this.age = age;
this.name = name;
}
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 int compareTo(StuComparable stu) {
return this.getAge() - stu.getAge();
}
}
【Comparator扩展类]:
class StuComparator implements Comparator<StuComparator> {
private int age;
private String name;
/**
* @param age
* @param name
*/
public StuComparator(int age, String name) {
this.age = age;
this.name = name;
}
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 int compare(StuComparator o1, StuComparator o2) {
return o1.getAge() - o2.getAge();
}
}
一.Collections.sort()
重写Comparable接口:比较2个对象的大小
ArrayList<StuComparable> arrayList = new ArrayList<StuComparable>();
arrayList.add(new StuComparable(6, "123"));
arrayList.add(new StuComparable(5, "456"));
arrayList.add(new StuComparable(4, "789"));
// 1.Sort方法用到了Comparable接口,Student重写Comparable接口方法,可以进行排序
// 解决方案一:如果StuComparable类不实现Comparable接口,会报错,因为sort中不知道如何对实
// 体类比较大小
// Collections.sort(arrayList );
// 解决方案二: Student类不实现Comparable接口,传进去一个Comparator接口对象
Collections.sort(arrayList , new Comparator<StuComparable>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getAge() - o2.getAge();
}
});
for (StuComparable stu : arrayList) {
System.out.println(MessageFormat.format("age:{0}", stu.getAge()));
}
二.TreeMap
重写Comparable接口:比较2个对象的大小
// 解决方案一:如果StuComparable类不实现Comparable接口,会报错,因为put中不知道如何对实体类进行比较
TreeMap<StuComparable, String> treeMap = new TreeMap<StuComparable, String>();
// 解决方案二: Student类不实现Comparable接口,传进去一个Comparator接口对象
// TreeMap<StuComparable, String> treeMap = new TreeMap<StuComparable, String>(new
// Comparator<StuComparable>() {
// public int compare(Student o1, Student o2) {
// return o1.getAge() - o2.getAge();
// }
// });
treeMap.put(new StuComparable(6, "kobe"), "kobe");
treeMap.put(new StuComparable(5, "jordan"), "jordan");
treeMap.put(new StuComparable(4, "davis"), "davis");
Set<Entry<StuComparable, String>> allSet = treeMap.entrySet();
for (Entry<StuComparable, String> entry : allSet) {
System.out.println(MessageFormat.format("key:{0},value:{1}", entry.getKey().getAge(), entry.getValue()));
}
三.Arrays.sort
重写Comparator接口:比较2个对象的大小
StuComparable[] stuArr = { new StuComparable(6, "123"), new StuComparable(5, "456"),
new StuComparable(4, "789") };
Arrays.sort(stuArr);
for (StuComparable stu : stuArr) {
System.out.println(MessageFormat.format("age:{0}", stu.getAge()));
}
输出结果:升序排序