java中Comparable 和Comparator
public interface Comparable<T> {
public int compareTo(T o);
}
实例:
x.compareTo(y) 来“比较x和y的大小”。若返回“负数”,意味着“x比y小”;返回“零”,意味着“x等于y”;返回“正数”,意味着“x大于y”。
如:
package bolg;
public class Person implements Comparable{
String name;
int age;
Person(String name,int age)
{
this.name=name;
this.age=age;
}
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 int compareTo(Object o) {
// TODO Auto-generated method stub
int i = 0;
i=name.compareTo(((Person)o).name);
if(0==i)
{
return age-((Person)o).age;
}
else {
return i;
}
}
}
Test
package bolg;
import java.util.Arrays;
public class TestPerson {
public static void main(String args[])
{
Person[] persons = new Person[] { new Person("a", 30), new Person("ab", 20) };
Arrays.sort(persons);
for (int i = 0; i < persons.length; i++) {
Person user = persons[i];
System.out.println(user.getName() + " " + user.getAge());
}
}
}
输出结果
a 30
ab 20
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
为什么可以不实现 equals(Object obj) 函数呢? 因为任何类,默认都是已经实现了equals(Object obj)的。 Java中的一切类都是继承于java.lang.Object,在Object.java中实现了equals(Object obj)函数;所以,其它所有的类也相当于都实现了该函数。
package bolg;
import java.util.Comparator;
public class PersonComparator implements Comparator{
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
return ((Person) o1).getAge() - ((Person) o2).getAge();
}
}
package bolg;
import java.util.Arrays;
public class TestPerson {
public static void main(String args[])
{
Person[] persons = new Person[] { new Person("a", 30), new Person("ab", 20) };
// Arrays.sort(persons);
Arrays.sort(persons,new PersonComparator());
for (int i = 0; i < persons.length; i++) {
Person user = persons[i];
System.out.println(user.getName() + " " + user.getAge());
}
}
}
ab 20
a 30
原文地址:http://blog.csdn.net/yujin753/article/details/44681331