java 自定义类比较器
示例:
package com.myfile;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by tengfei on 2017/10/27
*/
public class CompareTest {
/**
* 内部比较器:Comparable, 重写conpareTo方法
*/
@SuppressWarnings("rawtypes")
class Student1 implements Comparable {
private String name;
private int age;
public Student1(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "\tStudent1 age: " + age + ", name: " + name + "\r";
}
@Override
public int compareTo(Object o) {
Student1 tmp = (Student1) o;
int result = tmp.age < age ? 1 : (tmp.age == age ? 0 : -1);
return result = result == 0 ? (tmp.name.trim().compareTo(name.trim()) < 0 ? 1 : -1) : result;
}
}
// -------------------------------------------------------------------------------------
/**
* 外部比较器:Comparator, 定义comparator比较类
*/
class Student2 {
private String name;
private int age;
public Student2(int age, String name) {
this.age = age;
this.name = name;
}
@Override
public String toString() {
return "\tStudent2 age: " + age + ", name: " + name + "\r";
}
}
@SuppressWarnings("rawtypes")
public static class Student2Comparator implements Comparator {
public int compare(Object o1, Object o2) {
Student2 t1 = (Student2) o1;
Student2 t2 = (Student2) o2;
int result = t1.age > t2.age ? 1 : (t1.age == t2.age ? 0 : -1);
return result = result == 0 ? (t1.name.trim().compareTo(t2.name.trim()) > 0 ? 1 : -1) : result;
}
@SuppressWarnings("unchecked")
public static void main(String[] args) {
CompareTest co = new CompareTest();
List<Student1> list1 = new ArrayList<Student1>();
list1.add(co.new Student1(1, "aa"));
list1.add(co.new Student1(2, "abb"));
list1.add(co.new Student1(2, "acc"));
list1.add(co.new Student1(3, "dd"));
Collections.sort(list1); // 内部比较器:要排序的对象实现Comparable接口,可以对自身进行比较
System.out.println(list1);
List<Student2> list2 = new ArrayList<Student2>();
list2.add(co.new Student2(1, "aa"));
list2.add(co.new Student2(2, "abb"));
list2.add(co.new Student2(2, "acc"));
list2.add(co.new Student2(3, "dd"));
Collections.sort(list2, new Student2Comparator()); // 外部比较器:通过实现Comparator接口
System.out.println(list2);
}
}
}
版权声明:本文为lelewufei原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。