ArrayIndexOutOfBoundsException when using the ArrayList's iterator [duplicate] ArrayIndexOutOfBoundsException when using the ArrayList's iterator [duplicate] java java

ArrayIndexOutOfBoundsException when using the ArrayList's iterator [duplicate]


Am I doing that right, as far as iterating through the Arraylist goes?

No: by calling iterator twice in each iteration, you're getting new iterators all the time.

The easiest way to write this loop is using the for-each construct:

for (String s : arrayList)    if (s.equals(value))        // ...

As for

java.lang.ArrayIndexOutOfBoundsException: -1

You just tried to get element number -1 from an array. Counting starts at zero.


While I agree that the accepted answer is usually the best solution and definitely easier to use, I noticed no one displayed the proper usage of the iterator. So here is a quick example:

Iterator<Object> it = arrayList.iterator();while(it.hasNext()){    Object obj = it.next();    //Do something with obj}


List<String> arrayList = new ArrayList<String>();for (String s : arrayList) {    if(s.equals(value)){        //do something    }}

or

for (int i = 0; i < arrayList.size(); i++) {    if(arrayList.get(i).equals(value)){        //do something    }}

But be carefull ArrayList can hold null values. So comparation should be

value.equals(arrayList.get(i))

when you are sure that value is not null or you should check if given element is null.