ArrayIndexOutOfBoundsException when using the ArrayList's iterator

后端 未结 8 1190
甜味超标
甜味超标 2020-12-02 06:36

Right now, I have a program containing a piece of code that looks like this:

while (arrayList.iterator().hasNext()) {
     //value is equal to a String value         


        
8条回答
  •  渐次进展
    2020-12-02 07:20

    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.

提交回复
热议问题