日期:2014-05-20 浏览次数:20850 次
import java.util.*;
public class Compare{
public static void main(String[] args){
List l1=new LinkedList();
l1.add(new Name("Karl","M"));
l1.add(new Name("Steven","Lee"));
l1.add(new Name("Join","o"));
l1.add(new Name("Tom","M"));
System.out.println(l1);
Collections.sort(l1);
System.out.println(l1);
}
}
class Name implements Comparable{
private String firstname,lastname;
public Name(String firstname,String lastname){
this.firstname=firstname;
this.lastname=lastname;
}
public String getFirstname(){
return firstname;
}
public String getLastname(){
return lastname;
}
public String toString(){
return(firstname+" "+lastname);
}
public boolean equals(Object obj){
if(obj instanceof Name){
Name name=(Name)obj;
return(firstname.equals(name.firstname))&&(lastname.equals(name.lastname));
}
return super.equals(obj);
}
public int hashCode(){
return firstname.hashCode();
}
public int CompareTo(Object o){
Name n=(Name)o;
int lastCmp=lastname.compareTo(n.lastname);
return(lastCmp!=0?lastCmp:firstname.compareTo(n.firstname));
}
}