Chinaunix首页 | 论坛 | 博客
  • 博客访问: 742934
  • 博文数量: 130
  • 博客积分: 2951
  • 博客等级: 少校
  • 技术积分: 1875
  • 用 户 组: 普通用户
  • 注册时间: 2010-03-04 18:32
文章分类

全部博文(130)

文章存档

2013年(1)

2012年(129)

分类: Java

2012-02-21 18:07:36

static
>
void
( list)
          根据元素的自然顺序 对指定列表按升序进行排序。 
static
void
( list,  c)
          根据指定比较器产生的顺序对指定列表进行排序。

  1. package intro.collections;

  2. import java.util.Collections;
  3. import java.util.Comparator;
  4. import java.util.LinkedList;

  5. class Test implements Comparable{
  6.     public int t;
  7.     public Test(int t){
  8.         this.t = t;
  9.     }
  10.     @Override
  11.     public int compareTo(Object arg0) {
  12.         Test t1 = (Test)arg0;        
  13.         return (this.t < t1.? 1 : (this.t == t1.t ? 0 : -1));
  14.     }    
  15. }

  16. public class LindedListTest {
  17.     public static void main(String [] args){
  18.         LinkedList<Test> list1 = new LinkedList<Test>();
  19.         list1.add(new Test(5));
  20.         list1.add(new Test(3));
  21.         list1.add(new Test(4));
  22.         
  23.         Collections.sort(list1); //用自然排序要求List内被排序的Object实现了Comparable接口
  24.         
  25.         for(Test t : list1){
  26.             System.out.println(t.t);
  27.         }
  28.         
  29.         Collections.sort(list1, new Comparator<Test>(){ //也可以用自定义排序,实现Comparator接口
  30.             public int compare(Test t0, Test t1) {
  31.                 return (t0.t > t1.? 1 (t0.t == t1.t ? 0 : -1));
  32.             }
  33.         });
  34.         
  35.         for(Test t : list1){
  36.             System.out.println(t.t);
  37.         }
  38.         
  39.     }
  40.     
  41. }
阅读(1213) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~