通过比较元素找到最小值并将其放入另一个使用两个循环排序的向量中,我遇到了一些问题,特别是我一直使用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);
我的想法是用一个循环找到最小值,然后将它添加到排序后的向量中,然后在另一个循环中继续这样做,直到第一个向量中没有更多的元素,并在每次找到新的最小元素时将其删除。但是它不起作用。
发布于 2019-03-22 04:19:08
问题是您的代码永远不会在外部do
- while
循环的迭代之间重置MIN
和indice
。由于代码从不更新MIN
,第二次迭代无意中重用了indice
的旧值,最终导致removeElementAt
中出现索引越界异常。
解决这个问题的一种方法是在进入for
循环之前将indice
设置为0,将MIN
设置为myList.get(0)
。实际上,您应该将indice
和MIN
声明移到do
- whole
循环中,因为这是它们的正确作用域。
最后,if
的主体周围缺少大括号,这对功能没有影响,但会导致冗余处理。
注:,我假设您正在编写自己的sort作为学习练习。否则,您应该使用Java库函数或对集合进行排序。
https://stackoverflow.com/questions/55288574
复制相似问题