Java:遍历集合元素
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Driver {
public static void main(String[] args) {
// List<String> bigCities=new ArrayList<String>();
List<String> bigCities=new ArrayList<>();
bigCities.add("北京");
bigCities.add("上海");
bigCities.add("深圳");
System.out.println(bigCities.size());
// 遍历元素方式01
System.out.println(bigCities); //打印结果
bigCities.add(1,"纽约");
System.out.println(bigCities); //打印结果
bigCities.add(1,"伦敦");
System.out.println(bigCities); //打印结果
// 遍历元素方式02
for (int i = 0; i <bigCities.size() ; i++) {
System.out.print(bigCities.get(i)+"\t");
}
System.out.println();
// 遍历元素方式03
for (String bigCity1 : bigCities) {
System.out.print(bigCity1+"\t");
}
System.out.println();
// 遍历元素方式04
bigCities.forEach(System.out::println);
System.out.println();
// 遍历元素方式05
Iterator iterator=bigCities.iterator();//得到迭代器对象
while (iterator.hasNext()){
System.out.print(iterator.next()+"\t");
}
System.out.println();
// 遍历元素方式06
for (Iterator iterator1=bigCities.iterator();iterator1.hasNext();){
System.out.print(iterator1.next()+"\t");
}
}
}
posted on 2019-06-10 00:33 Indian_Mysore 阅读(138) 评论(0) 编辑 收藏 举报