JAVA 使用 .compareTo 对向量进行排序并填充另一个向量

JAVA Sorting a vector with .compareTo and by filling another vector

我在通过比较找到最小值的元素并将其放入另一个将使用两个循环排序的向量来排序向量时遇到了一些问题,特别是我一直有 ArrayIndexOutOfBoundsException。

Vector<Figure> myList = new Vector<Figure>(); //this is the vector with all the unsorted geometric shapes
Vector<Figure> listordered = new Vector<Figure>(); //the vector where i want to put them sorted
        Figure x = null;
        int indice = 0;
        System.out.println(myList.size());
        do{
        for(int i=0;i<myList.size();i++) {
            x = myList.get(i);
              if(x.compareTo(MIN) <0)
                MIN=x;
                indice = myList.indexOf(MIN);
        }
        listordered.add(MIN);
        myList.removeElementAt(indice);
        System.out.println(myList.size());
        }while(myList.size()!=0);

        System.out.println(listordered);

我的想法是用一个循环找到最小值,然后将其添加到已排序的向量中,然后用另一个循环继续这样做,直到第一个向量中没有更多元素,并在每次找到新的最小元素时删除。但它不起作用。

问题是您的代码从不在外部 do - while 循环的迭代之间重置 MINindice。由于代码从不更新 MIN,第二次迭代无意中重用了 indice 的旧值,最终导致 removeElementAt.

中的索引越界异常

解决此问题的一种方法是在进入 for 循环之前将 indice 设置为零,将 MIN 设置为 myList.get(0)。事实上,您应该将 indiceMIN 声明移动到 do - whole 循环中,因为这是它们的正确范围。

最后,if 正文周围缺少花括号。这对功能没有影响,但会导致冗余处理。

注意:我假设您正在编写自己的排序作为学习练习。否则你应该使用 Java 库函数或排序集合。