java实现voctor按指定方式排序示例分享
程序员文章站
2024-02-23 20:40:40
复制代码 代码如下:import java.util.*;class mycompare implements comparator //实现comparator,定义自己...
复制代码 代码如下:
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()<e2.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());
}
}
下一篇: Java 中IO流字符流详解及实例