java完成voctor按指定方法排序示例分享。本站提示廣大學習愛好者:(java完成voctor按指定方法排序示例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是java完成voctor按指定方法排序示例分享正文
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());
}
}