代码:
import java.io.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
class Box{
public float score;
}
class BoxComparator implements Comparator<Box> {
public int compare(Box a, Box b) {
if(a.score < b.score){
return 1;
}else if(a.score == b.score){
return 0;
}else{
return -1;
}
}
}
class test
{
public static void main (String[] args) throws java.lang.Exception
{
Vector<Box> boxes = new Vector<Box>();
Box b1 = new Box();
b1.score = 0.1f;
Box b2 = new Box();
b2.score = 0.2f;
Box b3 = new Box();
b3.score = 0.3f;
Box b4 = new Box();
b4.score = 0.4f;
boxes.add(b1);
boxes.add(b2);
boxes.add(b3);
boxes.add(b4);
Comparator<Box> cmp =new BoxComparator();
Collections.sort(boxes, cmp);
for(int i=0; i<boxes.size();i++){
Box box = boxes.get(i);
System.out.printf("%f\n",box.score);
}
}
}
输出:
0.400000
0.300000
0.200000
0.100000
修改BoxComparator中的compare函数可以改变为顺序或逆序排序
参考链接:
https://blog.csdn.net/da_kao_la/article/details/79548867
网友评论