for (int i = 0; i < list.size(); i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(j).compareTo(list.get(i)) > 0) { String tmp = list.get(i); list.remove(i); list.add(i, list.get(j)); list.remove(j); list.add(j, tmp); } } } 

Exception in thread "java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 at java.util.ArrayList.rangeCheck (Unknown Source) at java.util.ArrayList.get (Unknown Source) at Task1.main (Task1. java: 30)

  • Try Collections.sort(list) . - VladD

3 answers 3

In general, the answer to your question is contained in the stackrack you mentioned:

java.lang.IndexOutOfBoundsException: Index: 3, Size: 3 at java.util.ArrayList.rangeCheck (Unknown Source) at java.util.ArrayList.get (Unknown Source) at Task1.main ( Task1.java:30 )

Apparently, an exception occurs on the line

 list.add(i, list.get(j)); 

where you are trying to get the j-th element of the collection, not taking into account that the previous line, namely:

 list.remove(i); 

You have reduced the number of elements in it.

     at Task1.main(Task1.java:30) 

    In the Task1 class of the main () method line 30

      Why not just do this:

        for (int i = 0; i < list.size(); i++) { for (int j = i + 1; j < list.size(); j++) { if (list.get(j).compareTo(list.get(i)) > 0) { String tmp = list.get(i); list.add(i, list.get(j)); list.add(j, tmp); } } } 

      The code will do the same, only there will be no exceptions.

      • True, something tells me that it will cycle ...) In general, if anything, debugging you to help - Stas0n
      • As far as I understand, if you add an index to the ArrayList Element by 0, then all the elements of the sheet will shift to the right, and the length will increase by one. - JAVAvladuxa