package com.hqy.String;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/*
Java集合遍历:
1. 使用迭代器
2.使用for-each循环
3.使用forEach()方法
*/
public class JavaJihe {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> strs=new ArrayList<>();
strs.add("hello");
strs.add("world");
strs.add("good");
System.out.println(" 1.使用迭代器:");
// 1.使用迭代器
// Collection接口中的iterator()方法获取集合的迭代器
//iterator()方法获取集合的迭代器
Iterator<String> strsIterator=strs.iterator();
while(strsIterator.hasNext()){//集合中有更多元素要迭代, hasNext()方法将返回true。否则,它返回false。
//next()方法返回集合中的下一个元素。我们应该在调用 next()方法之前调用 hasNext()方法。
String str=strsIterator.next();
System.out.println(str);
}
/*迭代器注意事项:
迭代器是一次性对象。我们不能重置迭代器,它不能被重用。
要再次遍历同一集合的元素,请通过调用集合的iterator()方法来创建一个新的Iterator。
*/
Iterator<String> strsIterator2=strs.iterator();
while(strsIterator2.hasNext()){//集合中有更多元素要迭代, hasNext()方法将返回true。否则,它返回false。
//next()方法返回集合中的下一个元素。我们应该在调用 next()方法之前调用 hasNext()方法。
String str=strsIterator2.next();
System.out.println(str);
strsIterator2.remove();
}
System.out.println(strs);
System.out.println(" 2.使用for-each循环:");
//2.使用for-each循环
//注意:我们不能使用for-each循环从集合中删除元素。否则将抛出ConcurrentModificationException异常:
strs.add("python");
strs.add("java");
strs.add("c++");
for(String s:strs){
System.out.println(s);
}
System.out.println(" 3.使用forEach()方法:");
//3.使用forEach()方法
strs.forEach(System.out::println);
}
} 结果输出:
1.使用迭代器:
helloworld
good
hello
world
good
[]
2.使用for-each循环:
python
java
c++
3.使用forEach()方法:
python
java
c++
2869

被折叠的 条评论
为什么被折叠?



