public class Person implements Comparable { String name; int age public int compareTo(Person another) { int i = 0; i = name.compareTo(another.name); // 使用字符串的比较 if(i == 0) { // 如果名字一样,比较年龄, 返回比较年龄结果 return age - another.age; } else { return i; // 名字不一样, 返回比较名字的结果. } } }
public class Person{ String name; int age } class PersonComparator implements Comparator { public int compare(Person one, Person another) { int i = 0; i = one.name.compareTo(another.name); // 使用字符串的比较 if(i == 0) { // 如果名字一样,比较年龄,返回比较年龄结果 return one.age - another.age; } else { return i; // 名字不一样, 返回比较名字的结果. } } }
Java--comparator接口与Comparable接口的区别
原文地址:http://blog.csdn.net/yayun0516/article/details/46048753