当前位置: 代码迷 >> J2SE >> 如何给Vector里面的元素排序 有现成的方法吗
  详细解决方案

如何给Vector里面的元素排序 有现成的方法吗

热度:331   发布时间:2016-04-24 17:18:16.0
怎么给Vector里面的元素排序 有现成的方法吗
怎么给Vector里面的元素排序   有现成的方法吗?

------解决方案--------------------
static void sort(List list)
Sorts the specified list into ascending order, according to the natural ordering of its elements.
static void sort(List list, Comparator c)
Sorts the specified list according to the order induced by the specified comparator.
------解决方案--------------------
自己写个比较器,建议lz不要使用冒泡法。冒泡法的时间复杂度太大。

因为
public class Vector extends AbstractList
implements List, RandomAccess, Cloneable, java.io.Serializable

具体代码参考一下
//: c11:DirList.java
// Displays directory listing.
// From 'Thinking in Java, 3rd ed. ' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
package org.luyang.collections;

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

public class Sort {
public static String sort1 = "BIG_TO_SMALL ";

public static String sort2 = "SMALL_TO_BIG ";

public static void main(String[] args) {

Vector vec = new Vector();
vec.add( "2 ");
vec.add( "3 ");
vec.add( "1 ");
Collections.sort(vec, new AlphabeticComparator1(sort1));
for (int i = 0; i < vec.size(); i++) {
System.out.println(vec.get(i));
}
}
}

class AlphabeticComparator1 implements Comparator {
String sort = null;

public AlphabeticComparator1(String sort) {
this.sort = sort;
}

public int compare(Object o1, Object o2) {
String s1 = (String) o1;
String s2 = (String) o2;
if ( "SMALL_TO_BIG ".equalsIgnoreCase(sort)) {
return s1.toLowerCase().compareTo(s2.toLowerCase());
} else {
return s1.toLowerCase().compareTo(s2.toLowerCase()) * -1;
}
}
}