`
xurichusheng
  • 浏览: 335785 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

Vector排序

阅读更多

 

1. Vector 默认按元素的添加顺序排序

import java.util.Vector;

public class TestVector {
  
    public static void main(String[] args) {

        Vector<Integer> e = new Vector<Integer>(10);
        
        e.add(33);
        e.add(2);
        e.add(3);
        e.add(5);
        e.add(1);
        e.add(1);
        e.add(0);
        e.add(10);
        
        for (Integer elem: e) {
            System.out.println(elem);
        }
    }
}

 运行结果

33
2
3
5
1
1
0
10

 

2. 按升序排序

   2.1 要排序的对象     

public class Elem {

    private int val;
    
    public Elem(int val) {
        this.val = val;
    }
    
    public int getVal() {
        return val;
    }
}

    2.2 排序    

import java.util.Comparator;

public class ElemCompare implements Comparator<Elem> {

    @Override
    public int compare(Elem o1, Elem o2) {

        /*升序*/
        
        if (o1.getVal() < o2.getVal()) {
            return -1;
        } else if (o1.getVal() > o2.getVal()) {
            return 1;
        }
        
        return 0;
    }
}

   2.3 测试    

import java.util.Collections;
import java.util.Vector;

public class TestVector {

    public static void main(String[] args) {

        Vector<Elem> e = new Vector<Elem>(10);
        
        e.add(new Elem(33));
        e.add(new Elem(2));
        e.add(new Elem(3));
        e.add(new Elem(5));
        e.add(new Elem(1));
        e.add(new Elem(1));
        e.add(new Elem(0));
        e.add(new Elem(10));
        
        Collections.sort(e, new ElemCompare());
        
        for (Elem elem: e) {
            System.out.println(elem.getVal());
        }
    }
}

    2.4 运行结果

     

0
1
1
2
3
5
10
33

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics