下一页 1 2 3 4 5 6 7 8 9
编写你自己的 Comparable 类型
Comparable 接口由一个单一的方法构成:
public interface Comparable {
public int compareTo(Object o);
}
compareTo 方法将接收对象与特定对象进行比较,并在接收对象小于、等于或大于特定对象时分别返回负整数、空或一个正整数。如果特定对象不能与接收对象相比较,该方法扔出一个ClassCastException.
这是一个表示某人姓名的类(a class representing a person"s name), 它实现了 Comparable:
import java.util.*;
public class Name implements Comparable {
private String firstName, lastName;
public Name(String firstName, String lastName) {
if (firstName==null || lastName==null)
throw new NullPointerException();
this.firstName = firstName;
this.lastName = lastName;
}
public String firstName() {return firstName;}
public String lastName() {return lastName;}
public boolean equals(Object o) {
if (!(o instanceof Name))
return false;
Name n = (Name)o;
return n.firstName.equals(firstName) &&
n.lastName.equals(lastName);
}
public int hashCode() {
return 31*firstName.hashCode() + lastName.hashCode();
}
public String toString() {return firstName + " " + lastName;}
public int compareTo(Object o) {
Name n = (Name)o;
int lastCmp = lastName.compareTo(n.lastName);
return (lastCmp!=0 ? lastCmp :
firstName.compareTo(n.firstName));
}
}