【问题标题】:JAVA Sorting a vector with .compareTo and by filling another vectorJAVA用.compareTo对向量进行排序并填充另一个向量
【发布时间】:2019-03-21 20:12:20
【问题描述】:

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

问题是您的代码永远不会在外部 do - while 循环的迭代之间重置 MINindice。由于代码从不更新MIN,因此第二次迭代无意中重用了indice的旧值,最终导致removeElementAt中的索引越界异常。

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

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

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

【讨论】:

  • 哇,是的,解决了所有问题,非常感谢,是的,这是一个学习练习,显然要学到很多东西啊哈哈,再次感谢
猜你喜欢
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 2012-07-05
  • 2016-09-19
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多