[英]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
循环的迭代之间重置MIN
和indice
。 由于代码从不更新MIN
,因此第二次迭代无意间重用了indice
的旧值,最终导致removeElementAt
索引超出范围异常。
解决这个问题的一种方法是设置indice
零和MIN
到myList.get(0)
再进for
循环。 实际上,您应该在do
- whole
循环内移动indice
和MIN
声明,因为这是它们的适当范围。
最后,您缺少if
身体周围的花括号。 这对功能没有影响,但是会导致冗余处理。
注意:我假设您正在编写自己的排序作为学习练习。 否则,您应该使用Java库函数或排序集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.