import java.util.* ;
class Name {
private String firstName ;
private String 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 is :"+firstName+"\n"+
       "lastName is :"+lastName ;
}

public boolean equals(Object obj) {
if(obj instanceof Name) {
Name name = (Name)obj ;
return (firstName.equals(name.firstName))
       && (lastName.equals(name.lastName)) ;
  }
 else {
  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)) ;
}
} public class TestComparable {
public static void main(String args[]) {
List l1 = new LinkedList() ;
l1.add(new Name("tom","a")) ;
l1.add(new Name("jame","b")) ;
l1.add(new Name("kobe","c")) ;
System.out.println(l1) ;

System.out.println("---------------") ;
Collections.sort(l1) ;
System.out.println(l1) ;
}
}运行有问题,抛异常,请大虾指点。

解决方案 »

  1.   


    import java.util.* ;
    class Name implements Comparable{
    private String firstName ;
    private String 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 is :"+firstName+"\n"+
    "lastName is :"+lastName ; 
    }public boolean equals(Object obj) {
    if(obj instanceof Name) {
    Name name = (Name)obj ; 
    return (firstName.equals(name.firstName))
    && (lastName.equals(name.lastName)) ;
    }
    else {
    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)) ;
    }
    } public class TestComparable {
    public static void main(String args[]) {
    List l1 = new LinkedList() ;
    l1.add(new Name("tom","a")) ;
    l1.add(new Name("jame","b")) ;
    l1.add(new Name("kobe","c")) ;
    System.out.println(l1) ;System.out.println("---------------") ;
    Collections.sort(l1) ;
    System.out.println(l1) ;

    }
    Name 继承 Comparable 试试
      

  2.   

    static <T extends Comparable<? super T>> 
    void 
     sort(List<T> list) 
              根据元素的自然顺序 对指定列表按升序进行排序。 
    要用Collections.sort(l1) ;排序,这个l1对象要实现Comparable接口