Vector 中的元素如何进行排序呢?? 是有方法,还是需要自己写呢?? 我没有找到请高手指教!

解决方案 »

  1.   

    首先为Vector中的元素实现Comparator接口,实现compareTo和equals方法,
    然后用java.util.Arrays类的sort方法实现排序Vector v;
    //....
    java.util.Arrays.sort(v.toArray(),comparator);
      

  2.   

    下面是一个学生名字和成绩输入并排序的例子import java.util.*;
    import java.io.*;public class Student implements Comparable{
    private String name ="";
    private double score = 0;

    public Student (String name, double score){
    this.name = name;
    this.score = score;
    }

    public String getName(){
    return name;
    }

    public double getScore(){
    return score;
    }

    public int compareTo(Object o1){
    Student s1 = (Student)o1;

    if ( this.score > s1.getScore() ) return 1;
    if ( this.score < s1.getScore() ) return -1;
    return 0;
    }

    /* Comparator接口
        public int compare(Object o1,Object o2){
    Student s1 = (Student)o1;
    Student s2 = (Student)o2;

    if ( s1.getScore() > s2.getScore() ) return 1;
    if ( s1.getScore() < s2.getScore() ) return -1;
    return 0;
    }
    */

    public static void main(String[] args){

    Vector stuVector = new Vector();

    try
    {
    BufferedReader in =
             new BufferedReader(
               new InputStreamReader(System.in));
        
         Student s;
         String s1="";
         String s2="";
        
         System.out.println("Please input the 5 students' name and score!");
        
         for (int i=0; i<5; i++){   
        
          
         s1 = in.readLine() ;
         s2 = in.readLine() ;
         s = new Student(s1, Double.valueOf(s2).doubleValue());
         stuVector.add(s);
        
         System.out.println(" a student added!  name:"+ s1 + "  score:"+s2);
         } }
    catch(Exception e)
    {
    e.printStackTrace();
    }

    Collections.sort(stuVector); 

    System.out.println("The ordered Student name:");

       for(int i = 0;i<stuVector.size();i++){
        Student s = (Student)stuVector.get(i);
        System.out.println("  " + s.getName());
    }

    //System.in.read();

    }



    }
      

  3.   

    Arrays.sort(...)
    Collection.sort();
    YourOwn.sort(...) :P