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

问题描述 投票:1回答:1

我通过比较找到最小值的元素并将其放入另一个使用两个周期排序的向量中来排序向量时遇到了一些麻烦,特别是我一直有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);

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

java vector indexoutofboundsexception cycle
1个回答
0
投票

问题是你的代码永远不会在外部MIN - indice循环的迭代之间重置dowhile。由于代码永远不会更新MIN,第二次迭代无意中重用了indice的旧值,最终导致removeElementAt中的索引超出范围异常。

解决这个问题的一种方法是在进入indice循环之前将MIN设置为零,将myList.get(0)设置为for。实际上,你应该在indice - MIN循环中移动dowhole声明,因为这是它们的适当范围。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.