最近在项目中用到Vector,但是需要去排序,第一种方法可以去重写Comparator,在这个方法中去实现该对象中具体值得比较。代码如下:
public class MyCompare implements 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;
}
}
}
通过重写比较方法后,调用JAVA自身函数。java.util.Arrays.sort(vector,compare);.通过这个方法就可以排序。这也是很通用的。
由于我代码不能满足传值的需要,因为不是对象中的比较,是通过方法调用,比较出大小去排序。采用如下方法:
Vector<Elem> numbers = new Vector<Elem>();
// Vector<Integer> numbers1 = new Vector<Integer>();
numbers.add(new Elem(1));
numbers.add(new Elem(22));
numbers.add(new Elem(3));
numbers.add(new Elem(14));
Elem[] arr = new Elem[numbers.size()];
numbers.copyInto(arr);
Elem[] str = getSort(arr);
for (int i = 0; i < str.length; i++) {
System.out.println(str[i].get());
}
上面是主方法。首先是将Vector转换为数组,通过调用Vector.copyInfo().将Vector转换为数组,然后再用冒泡排序,去找到最小的值,然后交换。代码如下:
public static Elem[] getSort(Elem[] keys) {
for (int i = 0; i < keys.length - 1; i++) {
for (int j = 0; j < keys.length - i - 1; j++) {
Elem pre = keys[j];
Elem next = keys[j + 1];
if (pre.get() > next.get()) {
Elem temp = pre;
keys[j] = next;
keys[j + 1] = temp;
}
}
}
return keys;
}
通过这样两种方式可以满足去排序的问题了。