如何遍历集合中的元素
1.用数组的方式
- 通过toArray()方法将集合转换为一个Object类型的数组,然后对数组进行遍历
public void show(){//使用数组
Collection c =new ArrayList();
c.add("hello");
c.add("world");
c.add("java");
Object[] obj =c.toArray();
for(int i=0;i<obj.length;i++){
System.out.println(obj[i]);
}
}
hello
world
java
2.通过迭代器的方式
public void showA(){//使用迭代器
Collection c =new ArrayList();
c.add("hello");
c.add("world");
c.add("java");
Iterator ite =c.iterator();//此处it为一个迭代器对象,iterator()方法是java.lang.Iterable接口里面的,被Collection继承。
while(ite.hasNext()){ //hasNext();返回一个boolean值,如果集合中有元素,就返回true,如果没有就返回false
System.out.println(ite.next()); //next();返回下一个元素
}
}
hello
world
java
并发修改异常
- 我们在用迭代器遍历集合时,如果使用集合中的方法修改了集合(增删),这时就会产生一个异常。
public void addElemShowIterException(){
Collection c =new ArrayList();
c.add("hello");
c.add("world");
c.add("java");
Iterator ite =c.iterator();
while(ite.hasNext()){
String s =(String)(ite.next());
if(s.equals("java")){
c.add("你好");
}
}
System.out.println(c.toString());
}
Exception in thread "main" java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(Unknown Source)
2.解决方法:
我们需要找到一个迭代器自身的方法,在list接口下我们可以找到一个listIterator方法.如果想在遍历的过程中修改元素,就可以使用此方法.这样就不会产生异常。
public void addElemShowListIter(){
ArrayList<String> array =new ArrayList<>();
array.add("hello");
array.add("world");
array.add("java");
ListIterator list =array.listIterator();
while(list.hasNext()){//遍历
if(list.next().equals("java")){
list.add("你好");//使用迭代器对象添加
}
}
System.out.println(array.toString());
}
[hello, world, java, 你好]