-5

I have a problem with this code

    List<String> listaTags = new ArrayList<String>();





    int i = 0;
    String current = listaTags.get(i);

    while (listaTags.size() > 1 && listaTags.contains("/".concat(current)) != current.contains("/")) {

        if (current.equals(listaTags.get(i + 1))) {

            listaTags.remove(current);
            listaTags.remove(listaTags.get(i + 1));

            if (i < 0) {
                i++;
            }
        }

        i++;

    }

    System.out.println("errore nel codice");

}

listatags has six elements

the error is:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6,Size: 6

Can somebody help me?

Assafs
  • 3,257
  • 4
  • 26
  • 39
  • The `if (i < 0)` statement can be removed - there is no way i can be less than zero. Your IndexOutOfBoundsException probably happens after a few cycles in the loop - the value current never changes so the loop will go on forever (you probably want to have `String current =` inside the while loop. – Stefan Oct 16 '17 at 09:40
  • Indices in a list are zero-based, so if the list has 6 items, then valid index values are 0 to 5 (inclusive); 6 is an invalid index. – Jesper Oct 16 '17 at 09:41
  • if list has 6 elements, then indexes of those elements are from 0 to 5. Element 6 does not exist – mlecz Oct 16 '17 at 09:41

2 Answers2

0

this line

if (current.equals(listaTags.get(i + 1)))   

is throwing an exception because in 'while' every time list size is greater than 1 and your i value reaches the value which is greater than the size of the list.

Stanislav
  • 27,441
  • 9
  • 87
  • 82
sai
  • 75
  • 4
0

Since the Size of the list is 6, so indexes are 0,1,2,3,4,5 (which is value of i in this case)

You are always increasing the value of i by 1 and when it is i = 5, it is throwing IndexOutOfBoundsException.

As a fix you can do

if (i < 5 && current.equals(listaTags.get(i + 1))) {...}