ArrayIndexOutOfBoundsException when using the ArrayList's iterator

后端 未结 8 1192
甜味超标
甜味超标 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:21

    iterating using iterator is not fail-safe for example if you add element to the collection after iterator's creation then it will throw concurrentmodificaionexception. Also it's not thread safe, you have to make it thread safe externally.

    So it's better to use for-each structure of for loop. It's atleast fail-safe.

    0 讨论(0)
  • 2020-12-02 07:26

    You can also use like this:

    for(Iterator iterator = arrayList.iterator(); iterator.hasNext();) {
    x = iterator.next();
    //do some stuff
    }
    

    Its a good practice to cast and use the object. For example, if the 'arrayList' contains a list of 'Object1' objects. Then, we can re-write the code as:

    for(Iterator iterator = arrayList.iterator(); iterator.hasNext();) {
    x = (Object1) iterator.next();
    //do some stuff
    }
    
    0 讨论(0)
提交回复
热议问题