Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1449896
  • 博文数量: 254
  • 博客积分: 8696
  • 博客等级: 中将
  • 技术积分: 2961
  • 用 户 组: 普通用户
  • 注册时间: 2008-04-03 16:46
文章分类

全部博文(254)

文章存档

2015年(4)

2014年(18)

2013年(16)

2012年(8)

2011年(25)

2010年(2)

2009年(74)

2008年(107)

分类: Java

2008-07-09 23:37:13

Vector的排序:

import java.util.*;

class MyCompare implements Comparator //实现Comparator,定义自己的比较方法
{
public int compare(Object o1, Object o2) {
Elem e1=(Elem)o1;
Elem e2=(Elem)o2;

if(e1.get() > e2.get())//这样比较是降序,如果把-1改成1就是升序.
{
   return -1;
}
else if(e1.get(){
   return 1;
}
else
{
   return 0;
}
}
}

class Elem {
private int iVal;

public Elem(int i) {
   this.iVal = i;
}

public int get() {
   return this.iVal;
}
}

public class Vector1 {
public static void main(String[] args) {
   List v = new Vector();
   v.add(new Elem(1));
   v.add(new Elem(22));
   v.add(new Elem(3));
   v.add(new Elem(14));
   Comparator ct = new MyCompare();
   Collections.sort(v, ct);
   for (int i = 0; i < v.size(); i++)
    System.out.println(((Elem) v.get(i)).get());

}

}
(上述出自:http://hi.baidu.com/lirong1978/blog/item/ec9451161182194b21a4e975.html)

注意类Vector、Collections和接口Comparator的使用

阅读(7899) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~