集合框架遍历方式之——for-each循环
从Java5起,在Java中有了for-each循环,可以用来循环遍历collection和array。Foreach循环允许你在无需保持传统for循环中的索引,或在使用iterator /ListIterator(ArrayList中的一种迭代器实现)时无需调用while循环中的hasNext()方法就能遍历collection。for-each循环简化了任何Collection或array的遍历过程。但是使用foreach循环也有两点需要注意。
- 使用foreach循环的对象,必须实现了Iterable<T>接口
请看如下示例:
import java.util.ArrayList; public class ForeachTest1 { public static void main(String args[]) {
CustomCollection<String> myCollection = new CustomCollection<String>();
myCollection.add("Java");
myCollection.add("Scala");
myCollection.add("Groovy"); // What does this code will do, print language, throw exception or
// compile time error
for (String language : myCollection) {
System.out.println(language);
}
} private class CustomCollection<T> {
private ArrayList<T> bucket; public CustomCollection() {
bucket = new ArrayList();
} public int size() {
return bucket.size();
} public boolean isEmpty() {
return bucket.isEmpty();
} public boolean contains(T o) {
return bucket.contains(o);
} public boolean add(T e) {
return bucket.add(e);
} public boolean remove(T o) {
return bucket.remove(o);
} }
}
上述代码将无法通过编译,这是因为代码中的CustomCollection类没有实现Iterable<T>接口,编译期的报错如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Can only iterate over an array or an instance of java.lang.Iterable at Text.ForeachTest1.main(ForeachTest1.java:15)
事实上,无需等到编译时才发现报错,eclipse会在这段代码写完之后就会在foreach循环处显示错误:Can only iterate over an array or an instance of java.lang.Iterable
从上述示例可以再次得到确认的是,foreach循环只适用于实现了Iterable<T>接口的对象。由于所有内置Collection类都实现了java.util.Collection接口,已经继承了Iterable,所以为了解决上述问题,可以选择简单地让CustomCollection实现Collection接口或者继承AbstractCollection。解决方式如下:
import java.util.AbstractCollection;
import java.util.ArrayList;
import java.util.Iterator; public class ForeachTest {
public static void main(String args[]) {
CustomCollection<String> myCollection = new CustomCollection<String>();
myCollection.add("Java");
myCollection.add("Scala");
myCollection.add("Groovy");
for (String language : myCollection) {
System.out.println(language);
}
} private static class CustomCollection<T> extends AbstractCollection<T> {
private ArrayList<T> bucket; public CustomCollection() {
bucket = new ArrayList();
} public int size() {
return bucket.size();
} public boolean isEmpty() {
return bucket.isEmpty();
} public boolean contains(Object o) {
return bucket.contains(o);
} public boolean add(T e) {
return bucket.add(e);
} public boolean remove(Object o) {
return bucket.remove(o);
} @Override
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return bucket.iterator();
}
}
}
2.foreach循环的内部实现也是依靠Iterator进行实现的
为了验证foreach循环是使用Iterator作为内部实现这一事实,我们依然采用本文最开始的实例进行验证:
public class ItaratorTest { public static void main(String[] args) {
Collection<String> list = new ArrayList<String>();
list.add("Android");
list.add("IOS");
list.add("Windows Mobile"); // example1
// Iterator<String> iterator = list.iterator();
// while (iterator.hasNext()) {
// String lang = iterator.next();
// list.remove(lang);
// } // example 2
for (String language : list) {
list.remove(language);
}
} }
程序运行时所报异常:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Text.ItaratorTest.main(ItaratorTest.java:22)
此异常正说明了for-each循环内部使用了Iterator来遍历Collection,它也调用了Iterator.next(),这会检查(元素的)变化并抛出ConcurrentModificationException。
总结:
- foreach循环通过iterator实现,使用foreach循环的对象必须实现Iterable接口
集合框架遍历方式之——for-each循环的更多相关文章
- Map集合的遍历方式:
迭代器来遍历 : entrySet() ; keySet(); values(); eg.HashMap<String,String> map = new HashMap<Strin ...
- Map集合的遍历方式以及TreeMap集合保存自定义对象实现比较的Comparable和Comparator两种方式
Map集合的特点 1.Map集合中保存的都是键值对,键和值是一一对应的 2.一个映射不能包含重复的值 3.每个键最多只能映射到一个值上 Map接口和Collection接口的不同 Map是双列集合的根 ...
- List集合的遍历方式
遍历List集合的三种方法 List list = new ArrayList(); list.add("aaa"); list.add("bbb"); lis ...
- day08 集合API | 遍历_ | 泛型 |增强For循环
集合(续) 集合间的操作 集合提供了如取并集,删交集,判断包含子集等操作 package collection; import java.util.ArrayList; import java.uti ...
- set的三种遍历方式-----不能用for循环遍历(无序)
set的三种遍历方式,set遍历元素 list 遍历元素 http://blog.csdn.net/sunrainamazing/article/details/71577662 set遍历元素 ht ...
- Java集合的遍历方式
Map的遍历 1.通过map.entrySet遍历Key和Value Map<Integer,Integer> map = new HashMap<>(); map.put(1 ...
- Java自学-集合框架 遍历
遍历ArrayList的三种方法 步骤 1 : 用for循环遍历 通过前面的学习,知道了可以用size()和get()分别得到大小,和获取指定位置的元素,结合for循环就可以遍历出ArrayList的 ...
- Day11_51_Collections工具类之sort方法和list集合的遍历方式
Collections工具类之sort方法 * 使用Collections工具类对List集合进行排序 Collections.sort(List集合) * Collections.sort()方法只 ...
- Java中List集合的三种遍历方式(全网最详)
List集合在Java日常开发中是必不可少的,只要懂得运用各种各样的方法就可以大大提高我们开发的效率,适当活用各种方法才会使我们开发事半功倍. 我总结了三种List集合的遍历方式,下面一一来介绍. 首 ...
随机推荐
- .net操作数据库,史上最牛逼的方法,你见过这种方法吗
免费分享给大家.下载地址在最下面. C# code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ...
- CodeBlocks安装及配置注意事项
在使用codeblocks的时候,网上一般只会提供CodeBlocks的项目文件,并不包括编译器和调试器,要使用CodeBlocks的完整功能需要在官网下载完整版. 如图可下载mingw版本. 进入C ...
- APNS 服务推送通知
1. 将app注册notification里面, 并从APNS上获取测试机的deviceToken. - (BOOL)application:(UIApplication *)application ...
- Spark Streaming资源动态申请和动态控制消费速率剖析
本期内容 : Spark Streaming资源动态分配 Spark Streaming动态控制消费速率 为什么需要动态处理 : Spark 属于粗粒度资源分配,也就是在默认情况下是先分配好资源然后再 ...
- logback笔记
logback的使用 logback是什么? Logback是由log4j创始人设计的又一个开源日志组件.logback当前分成三个模块:logback-core,logback- classic和l ...
- 通过SQL Server 2008数据库复制实现数据库同步备份
SQL Server 2008数据库复制是通过发布/订阅的机制进行多台服务器之间的数据同步,我们把它用于数据库的同步备份.这里的同步备份指的是备份服务器与主服务器进行 实时数据同步,正常情况下只使用主 ...
- git入门札记
分布式版本控制(个人主机即版本库,有一台作为“中央服务器”来方便“交换”修改,管理修改 而非文件) vs. SVN CVS git 安装后设置: git config - -global user. ...
- [转][译]关于CSS中的float和position和z-index
原文:http://learn.shayhowe.com/advanced-html-css/detailed-css-positioning 当构建页面排版时,有不同的方法可以使用.使用哪一种方法取 ...
- tp框架总结(四)
一 ajax的返回 调用实例: $this->ajaxReturn(返回数据,提示信息,操作状态); $this->ajaxReturn(返回数据,‘json’); js: <scr ...
- Redis3.0.1 Stable版本的集群部署(Mac)
本文档基于如下原始文档(CentOS)创建: http://blog.csdn.net/xu470438000/article/details/42971091 修改了一些路径的错误,补全了一些命令执 ...