对于一些自定义的类的对象需要一个标准来进行排序,这个标准就是Comparable接口。也就是说,所有可以进行排序的类都实现了Comparable接口,接口中只有一个方法public static int compareTo(E o),(返回0,表示this=obj;返回正数,表示this>obj;返回负数,表示this<obj),实现了Comparable接口的类通过实现compareTo方法确定该类的对象的排序方式。
public class CompareToTest {
public static void main(String[] args) {
List l1 = new LinkedList();
l1.add(new Name("u1","a1"));
l1.add(new Name("j2","b2"));
l1.add(new Name("df3","h3"));
l1.add(new Name("sd4","o4"));
Collections.shuffle(l1);
System.out.println(l1);
Collections.sort(l1);
System.out.println(l1);
}
}
Name类:
public class Name implements Comparable{
private String firstName;
private String lastName;
public Name(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
//当使用contains,removes时,需要在本类中重写equals方法
public boolean equals(Object o){
if(o instanceof Name){
Name name = (Name)o;
return (firstName.equals(name.firstName))&&(lastName.equals(name.lastName));
}
return super.equals(o);
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
//重写equals应该重写hashCode方法,两对象相互equals他们的hashCode必须相等;
//当一个对象作为索引(Map里的键)时要用hashCode
public int hashCode(){
return firstName.hashCode();
}
public String toString(){
return firstName+","+lastName;
}
public int compareTo(Object o){
Name name = (Name)o;
int lastcom = lastName.compareTo(name.lastName);
return (lastcom!=0?lastcom:firstName.compareTo(name.firstName));
}
}