Java 集合排序方法 集合…

来源:互联网 发布:蜂蜜和四叶草 知乎 编辑:程序博客网 时间:2024/06/06 05:49
  1. package v08;
  2.  
  3. import java.util.*;
  4. public class TestSort {
  5.  
  6.  public static void main(String[] args{
  7.   // TODO Auto-generated method stub
  8.   List l1 new LinkedList();
  9.   l1.add(new Name("Karl","M"));
  10.   l1.add(new Name("Steven","Lee"));
  11.   l1.add(new Name("John","O"));
  12.   l1.add(new Name("Tom","M"));
  13.   System.out.println(l1);////[Karl M, Steven Lee, John O, Tom M]
  14.   Collections.sort(l1);
  15.   System.out.println(l1);//[John O, Karl M, Steven Lee, Tom M]
  16.   List l2 new LinkedList();
  17.   l2.add("String");
  18.   l2.add(new Integer(100));
  19.   System.out.println(l2);//集合的toString方法就是每个元素(对象)的toString方法联合[String, 100]
  20.  
  21.   
  22.  
  23.  }
  24.  
  25. }
  26.  
  27. class Name implements Comparable{
  28.  
  29.  private String firstName,lastName;
  30.  
  31.  public int compareTo(Object obj){
  32.   Name name (Name) obj;
  33.         int a lastName.compareTo(lastName);
  34.         return a != a :
  35.           firstName.compareTo(name.firstName);
  36.  }
  37.  
  38.  public Name(String firstName,String lastName){
  39.   this.firstName firstName;
  40.   this.lastName lastName;
  41.  }
  42.  
  43.  public String getFirstName(){
  44.   return firstName;
  45.  }
  46.  public String getLastName(){
  47.   return lastName;
  48.  }
  49.  public String toString(){
  50.   return firstName +" lastName;
  51.  }
  52.  
  53.  public boolean equals(Object obj){
  54.   if (obj instanceof Name){
  55.    Name name (Name) obj;
  56.    return firstName.equals(name.firstName&&
  57.      lastName.equals(name.lastName);
  58.   }
  59.   return super.equals(obj);
  60.  }
  61.  public int hashCode(){
  62.   return firstName.hashCode();
  63.  }
  64. }
  65.  
0 0