Iterator错误:java.util.NoSuchElementException

时间:2022-12-13 20:34:14
代码如下:
 String pptFileName = null;

 for (Iterator<FileUploadBean> it = filesList.iterator(); it.hasNext();) {
	if(it.next().getId().toString().equals(method)){
	 pptFileName = it.next().getFilePath();}
 

运行时报错:

java.util.NoSuchElementException

Eclipse报错误代码定位到 pptFileName =it.next().getFilePath(); 然后才知道 it.next()方法出现一次就遍历到下一个元素,导致Iterator越界错误!

改正如下:

再定义一个变量来接收,就可以解决问题

for (Iterator<FileUploadBean> it = filesList.iterator(); it.hasNext();) {
	FileUploadBean fub = it.next();
	if (fub.getId().toString().equals(method)) {
		pptFileName = fub.getFilePath();}