Search code examples
javavectorindexoutofboundsexceptioncycle

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


I am having some trouble sorting a vector by comparing the elements finding the minimum and putting it in another vector that will be the sorted one using two cycles, in particular i keep having 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);

My idea was to find the minimum with a cycle then add it to the sorted vector and with another cycle keep doing this untill there were no more elements in the first vector and removing each time the new minimum element found. but it doesnt work.


Solution

  • The problem is that your code never resets MIN and indice between iterations of the outer do - while loop. Since the code never updates MIN, the second iteration unintentionally reuses the old value of indice, eventually causing index out of bounds exception in removeElementAt.

    One approach to fix this is to set indice to zero and MIN to myList.get(0) before going into the for loop. In fact, you should move indice and MIN declarations inside the do - whole loop, because this is their proper scope.

    Finally, you are missing curly braces around if's body. This has no effect on functionality, but results in redundant processing.

    Note: I assume that you are writing your own sort as a learning exercise. Otherwise you should use Java library functions or ordering collections.