给java 中的List排序

来源:互联网 发布:兼容性测试软件 编辑:程序博客网 时间:2024/05/20 23:40
  1. //主要用到: Collections.sort方法:
  2. package com.tom.compare;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.List;
  7. public class CompareClient {
  8.  /**
  9.   * @param args
  10.   */
  11.  public static void main(String[] args) {
  12.   // TODO Auto-generated method stub
  13.   List list = new ArrayList();
  14.   list.add(new Content(15000,"1asdfasd5000"));
  15.   list.add(new Content(10000,"10000"));
  16.   list.add(new Content(20000,"20000"));
  17.   list.add(new Content(30000,"30000"));
  18.   list.add(new Content(25000,"25000"));
  19.   list.add(new Content(13000,"13000"));
  20.   list.add(new Content(15000,"15000")); 
  21.   list.add(new Content(89000,"89000"));
  22.  
  23.   ContentComparator comp = new ContentComparator(); 
  24.   Collections.sort(list,comp);
  25.  
  26.   Content content;
  27.   for(int i = 0; i < list.size(); i++){
  28.    content = (Content)list.get(i);
  29.    System.out.println(" content.getName() " + content.getName());
  30.   }
  31.  }
  32. }
  33. package com.tom.compare;
  34. import java.util.Comparator;
  35. public class ContentComparator implements Comparator {
  36.  public int compare(Object o1, Object o2) {
  37.   // TODO Auto-generated method stub
  38.   Content c1 = (Content) o1;
  39.   Content c2 = (Content) o2;
  40.   if (c1.getKey() > c2.getKey()) {
  41.    return 1;
  42.   } else {
  43.    if (c1.getKey() == c2.getKey()) {
  44.     return 0;
  45.    } else {
  46.     return -1;
  47.    }
  48.   }
  49.  }
  50. }
  51. package com.tom.compare;
  52. public class Content {
  53.  private long key;
  54.  private String name;
  55.  public Content(long key, String name) {
  56.   this.key = key;
  57.   this.name = name;
  58.  }
  59.  public long getKey() {
  60.   return key;
  61.  }
  62.  public void setKey(long key) {
  63.   this.key = key;
  64.  }
  65.  public String getName() {
  66.   return name;
  67.  }
  68.  public void setName(String name) {
  69.   this.name = name;
  70.  }
  71. }
  72. 结果是:

     content.getName() 10000
     content.getName() 13000
     content.getName() 1asdfasd5000
     content.getName() 15000
     content.getName() 20000
     content.getName() 25000
     content.getName() 30000
     content.getName() 89000

原创粉丝点击