ArrayIndexOutOfBounds使用ArrayList的迭代器时的异常

现在,我有一个程序,其中包含一段代码,如下所示:

while (arrayList.iterator().hasNext()) {
     //value is equal to a String value
     if( arrayList.iterator().next().equals(value)) {
          // do something 
     }
}

就迭代ArrayList而言,我这样做对吗?

我得到的错误是:

java.lang.ArrayIndexOutOfBoundsException: -1
    at java.util.ArrayList.get(Unknown Source)
    at main1.endElement(main1.java:244)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(Unknown Source)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at javax.xml.parsers.SAXParser.parse(Unknown Source)
    at main1.traverse(main1.java:73)
    at main1.traverse(main1.java:102)
    at main1.traverse(main1.java:102)
    at main1.main(main1.java:404)

我会展示其余的代码,但它非常广泛,如果我没有正确地进行迭代,我会假设唯一的可能性是我没有正确初始化。ArrayList


答案 1

就迭代数组列表而言,我这样做对吗?

否:通过在每次迭代中调用两次,您一直在获得新的迭代器。iterator

编写此循环的最简单方法是使用 for-each 构造:

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

至于

java.lang.ArrayIndexOutOfBoundsException: -1

您刚刚尝试从数组中获取元素编号。计数从零开始。-1


答案 2

虽然我同意接受的答案通常是最好的解决方案,并且绝对更容易使用,但我注意到没有人显示迭代器的正确用法。所以这里有一个简单的例子:

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