怎么给Vector里面的元素排序 有现成的方法吗

VirusFu 2007-02-28 04:07:44
怎么给Vector里面的元素排序 有现成的方法吗?
...全文
634 13 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
key_hua 2008-05-15
  • 打赏
  • 举报
回复
学习到起
ThirdDimension 2008-05-15
  • 打赏
  • 举报
回复
Collections.reverseOrder();
yzzlijun 2008-05-15
  • 打赏
  • 举报
回复
嘿嘿..顶起
Kylixs 2007-03-01
  • 打赏
  • 举报
回复
又学到新东西了..
Collections.reverseOrder();
原来是有的,以前还自己重新写了一个Comparator
tjlee 2007-03-01
  • 打赏
  • 举报
回复
List list = new Vector();
list.add(...);
...
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp);
System.out.println(list);
luyang1016 2007-03-01
  • 打赏
  • 举报
回复
自己写个比较器,建议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;
}
}
}
VirusFu 2007-02-28
  • 打赏
  • 举报
回复
楼上的说得具体点怎么写
  • 打赏
  • 举报
回复
带一个参数就行了
VirusFu 2007-02-28
  • 打赏
  • 举报
回复
好 谢谢flyforlove
不过用Collections.sort 排序后是升序 那降序怎么用
flyforlove 2007-02-28
  • 打赏
  • 举报
回复
vector 本身就是个List,用不着转换
VirusFu 2007-02-28
  • 打赏
  • 举报
回复
除了 Collections.sort(List list)这个方法还有别的吗 ? 再把vector 转成List 太麻烦了
我自己写了冒泡 感觉不好
void sortVector(){
int i,j;
for(i=0;i<v.size()-1;i++){
for(j=0;j<v.size()-i-1;j++){
if(((String)v.get(j)).compareTo((String)v.get(j+1))<0){
String strLine = (String)v.get(j);
v.setElementAt((String)v.get(j+1),j);
v.setElementAt(strLine,j+1);
}
}
}
}
believefym 2007-02-28
  • 打赏
  • 举报
回复
是Collections类
believefym 2007-02-28
  • 打赏
  • 举报
回复
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.

62,635

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧