重写 compareTo方法如下:
public int compareTo(Object o) { Name n = (Name) o; int lastCmp = secondName.compareTo(n.secondName); return (lastCmp!=0 ? lastCmp:firstName.compareTo(n.firstName)); }
完整代码如下
import java.util.List; import java.util.LinkedList; import java.util.Collections; public class Test { 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("John","O")); l1.add(new Name("Tom","M")); System.out.println(l1); Collections.sort(l1); System.out.println(l1); /* Set s = new HashSet(); s.add("hello"); s.add("world"); s.add(new Name("f1","11")); s.add(new Integer(100)); */ /* s.add("hello"); s.add("hello"); */ //Set /* Set s1 = new HashSet(); Set s2 = new HashSet(); s1.add("a");s1.add("b");s1.add("c"); s2.add("d");s2.add("a");s2.add("b"); Set sn = new HashSet(s1); sn.retainAll(s2); Set su = new HashSet(s1); su.addAll(s2); System.out.println(sn); System.out.println(su); */ /* Collection c = new HashSet(); c.add("hello"); c.add(new Name("f1","11")); c.add(new Name("f2","12")); c.add(new Name("f3","13")); c.add(new Integer(100)); c.remove("hello"); c.remove(new Integer(100)); Iterator i = c.iterator(); while(i.hasNext()) { Name n = (Name)i.next(); System.out.print(n.getfirstName()+" "); }*/ /*System.out.println(c.remove(new Name("f1","11"))); System.out.println(c);*/ } } class Name implements Comparable { private String firstName,secondName; public Name(String firstName,String secondName) { this.firstName = firstName; this.secondName = secondName; } public String getfirstName() {return firstName;} public String getsecondName() {return secondName;} public String toString() { return firstName+" "+secondName; } public boolean equals(Object obj) { if(obj instanceof Name) { Name name = (Name) obj; return (firstName.equals(name.firstName))&&(secondName.equals(name.secondName)); } return super.equals(obj); } public int hashCode() { return firstName.hashCode(); } public int compareTo(Object o) { Name n = (Name) o; int lastCmp = secondName.compareTo(n.secondName); return (lastCmp!=0 ? lastCmp:firstName.compareTo(n.firstName)); } }