想对Vector排序,自己编了个算法 ,编译通过,可是在对某个VECTOR排序时出问题了:--------------------Configuration: <Default>--------------------
java.lang.ArrayIndexOutOfBoundsException: 5 >= 5
    at java.util.Vector.elementAt(Vector.java:417)
    at test.getDouble(test.java:164)
    at test.paixu(test.java:143)
    at test.main(test.java:252)
Exception in thread "main" 
Process completed.
程序如下:
private static double getDouble(Vector vector, int index) {
    return toDouble(vector.elementAt(index));
}private static Double toWrapDouble(double num) {
    return Double.valueOf(String.valueOf(num));
}private static double toDouble(Object obj) {
    return ((Double)obj).doubleValue();
}
  public static Vector paixu(Vector vector){
     double tem1,tem2,Ub;
     boolean Switch;
     Ub=vector.size();
     Switch=true;
     while(Switch==true){
     Switch=false;
     Ub=Ub-1;
     for(int i=0;i<=Ub-1;i++){
     if(getDouble(vector,i)>getDouble(vector,i+1)){
     Switch=true;
     tem1=getDouble(vector,i);
     tem2=getDouble(vector,i+1);
     vector.removeElementAt(i);
     vector.setElementAt(toWrapDouble(tem2),i);
     vector.removeElementAt(i+1);
     vector.setElementAt(toWrapDouble(tem1),i+1);
     }
     }
     }
     return vector;
    }
什么情况?帮忙改下下,大腕们!

解决方案 »

  1.   

    我知道有Collections.sort()可以对Vector进行排序,我想自己编个算法,帮忙看下
      

  2.   

    不要remove了,删除,列表会后面的元素会“上移”
      public static Vector paixu(Vector vector){
      double tem1,tem2,Ub;
      boolean Switch;
      Ub=vector.size();
      Switch=true;
      while(Switch==true){
      Switch=false;
      Ub=Ub-1;
      for(int i=0;i<=Ub-1;i++){
      if(getDouble(vector,i)>getDouble(vector,i+1)){
      Switch=true;
      tem1=getDouble(vector,i);
      tem2=getDouble(vector,i+1);
      //vector.removeElementAt(i);
      vector.setElementAt(toWrapDouble(tem2),i);
      //vector.removeElementAt(i+1);
      vector.setElementAt(toWrapDouble(tem1),i+1);
      }
      }
      }
      return vector;
      }
      

  3.   

    没有仔细看,但感觉下面执行后,vector中元素会越来越少,丢失了  
      vector.removeElementAt(i);
      vector.setElementAt(toWrapDouble(tem2),i);
      vector.removeElementAt(i+1);
      vector.setElementAt(toWrapDouble(tem1),i+1);或者不用removeElementAt 直接 setElementAt? 注意:setElementAt是替换不是添加