使用 ArrayList 的迭代器时出现 ArrayIndexOutOfBoundsException [英] ArrayIndexOutOfBoundsException when using the ArrayList's iterator

查看:27
本文介绍了使用 ArrayList 的迭代器时出现 ArrayIndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我有一个包含如下代码的程序:

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
     if( arrayList.iterator().next().equals(value)) {
          // do something 
     }
}

就遍历 ArrayList 而言,我做得对吗?

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

我得到的错误是:

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.

I would show the rest of the code, but it's pretty extensive, and if I am not doing the iteration correctly, I would assume the only possibility is that I am not initializing the ArrayList properly.

推荐答案

就遍历 Arraylist 而言,我做得对吗?

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

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

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

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

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

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

至于

java.lang.ArrayIndexOutOfBoundsException: -1

您只是尝试从数组中获取元素编号 -1.计数从零开始.

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

这篇关于使用 ArrayList 的迭代器时出现 ArrayIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆