一、为何需要实现Comparable接口
我们知道Collections类中包含很多对实现Collection接口容器各种操作的静态方法,最常用的莫过于排序(Collections.sort(List l))。
下面是个简答的例子:
public class Compare1{
public static void f(){
ArrayList arr = new ArrayList();
arr.add(10);
arr.add(23);
arr.add(7);
System.out.println(arr);
Collections.sort(arr);
System.out.println(arr);
}
}
若想用Collections.sort()方法对List中的元素进行排序时需要注意的是List里存放的元素对应的类必须已经实现了Comparable接口。
二、Comparable接口简介
Comparable接口内部只有一个要重写的关键的方法,为:
int compareTo(T o);
该方法只返回一个int型的值,例如 i = x.compareTo(y) ,如果i = 0,则表明x和y在排位上是相等的(并非意味着x.equals(y) = true, 但是jdk api上强烈建议这样处理)。
如果返回数值 i>0,则意味 x>y,反之若 i<0,意味x<y。
自定义类实现Comparable接口举例:
import java.util.ArrayList;
import java.util.Collections;
class Student implements Comparable
{
private String name;
private int ranking;
public Student(String name, int ranking)
{
this.name = name;
this.ranking = ranking;
}
public String toString()
{
return this.name+":"+this.ranking;
}
public int compareTo(Object o)
{
Student s = (Student)(o);
return this.ranking-s.ranking;
}
}
public class Compare2()
{
public static void f()
{
ArrayList arr = new ArrayList();
arr.add(new Student("Jack",10));
arr.add(new Student("Bill",23));
arr.add(new Student("Rudy",7));
System.out.println(arr);
Collectoins.sort(arr);
System.out.println(arr);
}
}