0
点赞
收藏
分享

微信扫一扫

集合遍历与迭代器注意事项--Java基础075


package com.sqf.conlection;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;


/*
练习: 使用三种方式遍历集合的元素.
第一种: 使用get方法遍历。 只用于ArrayList类
第二种: 使用迭代器正序遍历。
第三种: 使用迭代器逆序遍历。


迭代器在变量元素的时候要注意事项: 在迭代器迭代元素 的过程中,不允许使用集合对象改变集合中的元素 个数,
如果需要添加或者删除只能使用迭代器的方法进行操作。
如果使用过了集合对象改变集合中元素个数那么就会出现ConcurrentModificationException异常。

迭代元素 的过程中: 迭代器创建到使用结束的时间。
*/




public class Demo2 {

public static void main(String[] args) {

List list = new ArrayList();
list.add("张三");
list.add("小王");
list.add("哈哈");

//1.get
for(int i=0;i<list.size();i++){
System.out.print(list.get(i) + " ");
}
System.out.println();

//使用迭代器正序遍历。
ListIterator it = list.listIterator();
while(it.hasNext()){
System.out.print(it.next() + " ");
}
System.out.println();

// 使用迭代器逆序遍历。
while(it.hasPrevious()){
System.out.print(it.previous() + " ");
}


/*
//第一种: 错误
list.add("aa");
it.next();

//第二种: 正确
it.next();
list.add("aa");
原因?
在迭代器迭代元素 的过程中,不允许使用集合对象改变集合中的元素 个数,
如果需要添加或者删除只能使用迭代器的方法进行操作。
如果使用过了集合对象改变集合中元素个数那么就会出现ConcurrentModificationException异常。
*/


}

}


举报

相关推荐

0 条评论