import java.lang.Comparable;
import java.util.List;
import java.util.LinkedList;
import java.util.Collections;
public class TestCompareTo {
public static void main(String[] args) {
List l1 = new LinkedList();
l1.add(new Name("Karl", "M"));
l1.add(new Name("Stever", "Lee"));
l1.add(new Name("John", "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;
private String lastName;
Name(String firstName, String lastName) {
this.setFirstName(firstName);
this.setLastName(lastName);
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
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));
}
}
转载于:https://www.cnblogs.com/wjchang/archive/2012/05/01/3671708.html