現在,我已經包含了一段代碼,看起來像這樣的程序:ArrayIndexOutOfBoundsException異常時,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
。
在java 8中,你可以使用'forEach'方法:http://stackoverflow.com/questions/16635398/java-8-iterable-foreach-vs-foreach-loop –