集合框架遍历方式之——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集合的遍历方式,下面一一来介绍. 首 ...
随机推荐
- w3svc服务启动 不了,错误 1068:依赖服务或组件无法启动
win10系统,装了iis就是启动不了,报错误 1068:依赖服务或组件无法启动. 各种实验无法使用,最后如下方法解决 运行命令regedit,打开注册表编辑器,进入:HKEY_LOCAL_MACHI ...
- linux svn hooks代码自动更新至项目
由于开发移动端web,ui需要及时看到样式变化,所以通过svn hooks(钩子)来提交文件,然后再把文件同步到测试服务器项目目录,步骤如下: 1.进入 /home/svn/cmall/hooks ( ...
- leetcode-【中等题】2. Add Two Numbers
题目 You are given two linked lists representing two non-negative numbers. The digits are stored in re ...
- JS实现div动态水平垂直居中
在做页面的过程中,在很多地方都会遇到元素需要水平垂直的居中这个问题,之前总是去网上搜别人的代码,今天仔细研究了一下,分享给大家,先写一个简单的例子: <div class="mui-c ...
- 解决在CentOS6.5下安装OpenStack(Icehouse版本 )出现的glance服务无法正常工作的问题
最近一直在用Juno版本,因为项目需要,今天在虚拟机里安装了Icehouse版,其中glance组件在执行安装的过程后,出现启动失败的现象,幸好以前排查过此类错误,遂记录如下: 在官方文档(Iceho ...
- your PC ran into a problem and needs to restart system_thrread_exception_not_handled
- 用ionic快速开发hybird App(已附源码,在下面+总结见解)
1.ionic简介 ionic 是用于敏捷开发APP的解决方案.核心思路是:利用成熟的前端开发技术,来写UI和业务逻辑.也就是说,就是一个H5网站,这个区别于react-native,native.即 ...
- 脚本工具: 查看当前系统被写入的FD
#!/bin/bash touch /tmp/sn2 /tmp/sn4 /tmp/sn6 /tmp/sn3 redir=/dev/null which lsof >&/dev/null ...
- linux top命令中各cpu占用率含义
linux top命令中各cpu占用率含义 [尊重原创文章摘自:http://www.iteye.com/topic/1137848]0.3% us 用户空间占用CPU百分比 1.0% sy 内核空间 ...
- Setup QT 5.5.1 + OpenCV 3.0 + Visual Studio 2013 on windows 10
1. Install Visual studio 2013 community version which is free to use for personal usage. 2. Setup th ...