我是靠谱客的博主 奋斗花卷,这篇文章主要介绍java基础篇(4)加强型for循环与Iterator,现在分享给大家,希望可以做个参考。

引言

从JDK1.5起,增加了加强型的for循环语法,也被称为 “for-Each 循环”。加强型循环在操作数组与集合方面增加了很大的方便性。那么,加强型for循环是怎么解析的呢?同时,这是不是意味着基本for循环就会被取代呢?

语法:

复制代码
1
2
3
4
for(var item:items){//var 代表各钟类型 //相关操作 }

一、数组中的 for-Each 循环

我们先来看一下数组中的 for-Each 循环的使用;

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
String str[]= new String[]{"1","2","3"}; //普通for循环 for(int i=0;i<str.length;i++){ String item = str[i]; item += "str"; System.out.println(item); } //加强型for循环 for(String item:str){ item += "str"; System.out.println(item); }

通过比较上面例子中的两种类型的for循环,可以看出,for-Each 循环编写起来更加简单,更加方便程序员。因此,在程序中,应该多使用加强型循环。

回答一下上面提出的两个问题:

1、编译器是怎么处理数组中的for-Each循环的?

事实上,在数组中的 for-Each 最终会被编译器处理成一个普通的for循环,也就是说 for-Each循环是完全与普通for循环等价的,没有任何特殊的命令。
可以通过反编译来验证,很简单,此处不再多说。

2、在数组中,for-Each 循环能否完全替代普通for循环

答案是否定的。虽然for-Each 写起来方便,但也有以下几个局限性:

  • 只能对元素进行顺序的访问;
  • 只能访问数组或集合中的所有元素;
  • 循环中没有当前的索引,无法对指定的元素操作。如更换当前索引位置的元素。

二、集合中的 for-Each循环

数组的加强型的for-Each循环很简单,我们再来看一下集合中的for-Each 循环又是怎么样的。我们都知道集合中的遍历都是通过迭代(iterator)完成的。也许有人说,也可以按照下面的方式来遍历集合,不一定非要使用迭代:

复制代码
1
2
3
4
5
6
7
8
9
List<String> list = new LinkedList<String>(); list.add("a"); list.add("b"); list.add("c"); for(int i=0;i<list.size();i++){ String item = list.get(i); System.out.println(item); }

然而,这种方式对于基于链表实现的List来说,是比较耗性能的,因为get(int i)方法包含了一个循环,而且这个循环就是迭代遍历一次List,直到遇到第i个元素,才停止循环,返回第i个元素。对于数量小,遍历不频繁的List来说,开销可以忽略。否则,开销将不容忽视。

所以,正确集合遍历是使用迭代器Iterator来遍历的:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
List<String> list = new LinkedList<String>(); list.add("a"); list.add("b"); list.add("c"); //获取集合的迭代器 Iterator<String> itor = list.iterator(); //集合的普通for循环 for(;itor.hasNext();){//相当于 while(itor.hasNext()) String item = itor.next(); System.out.println(item); }

再看看对应的for-Each循环的例子:

复制代码
1
2
3
4
5
6
7
8
9
List<String> list = new LinkedList<String>(); list.add("a"); list.add("b"); list.add("c"); for(String item:list){//for-Each System.out.println(item); }

可以看出,for-Each循环比普通for循环要简洁很多。我们依旧回答上面的两个问题:

  1. 编译器是如何处理 集合中的for-Each循环的?
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
public static void main(String args[]) { List list = new LinkedList(); list.add("aa"); list.add("bb"); for(String item:list) { if("bb".equals(item)) list.add("cc"); } }

我们看一下上面例子的 反编译代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
public static void main(String args[]) { List list = new LinkedList(); list.add("aa"); list.add("bb"); for(Iterator iterator = list.iterator(); iterator.hasNext();) { String item = (String)iterator.next(); if("bb".equals(item)) list.add("cc"); } }

与数组类似,编译器最终也就是将集合中的for-Each循环处理成集合的普通for循环。 而集合的Collection接口通过扩展Iterable接口来提供iterator()方。那么我们换一个角度,是不是只要实现 Iterable接口,提供iterator()方法,也可以使用 for-Each循环呢?来看个例子:

复制代码
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
class MyList<T> implements Iterable<T>{ private ArrayList<T> list = new ArrayList<>(); public void addId(T id){ list.add(id); } public boolean removeId(T id){ return list.remove(id); } @Override public Iterator<T> iterator() {//扩展自Iterable接口 //为了简单起见,就直接使用已有的迭代器 return list.iterator(); } public static void main(String[] args) { MyList<String> myList = new MyList<>(); myList.addId("666999"); myList.addId("973219"); //for-Each for(String item:myList){ System.out.println(item); } } }

上面的例子编译通过,并且运行无误。所以,只要实现了Iterable接口的类,都可以使用for-Each循环来遍历。

集合迭代的陷阱

集合循环遍历时所使用的迭代器Iterator有一个要求:**在迭代的过程中,除了使用迭代器(如:Iterator.remove()方法)对集合增删元素外,是不允许直接对集合进行增删操作。**否则将会抛出 ConcurrentModificationException异常。所以,由于集合的for-Each循环本质上使用的还是Iterator来迭代,因此也要注意这个陷阱。for-Each循环很隐蔽地使用了Iterator,导致程序员很容易忽略掉这个细节,所以一定要注意。看下面的例子,for-Each循环中修改了集合。

复制代码
1
2
3
4
5
6
7
8
9
10
11
public static void main(String[] args) { List<String> list = new LinkedList<>(); list.add("aa"); list.add("bb"); for (String item : list) {//for-Each if ("bb".equals(item)) { list.add("cc"); //直接操作list } } }

运行抛出异常:

img

上面仅仅是

单线程

下的情况,如果你有并发编程的基础的话,就会知道:在 多线程 的环境中,线程是交替运行的(时间片轮转调度)。这就意味着,如果有两个线程A、B,线程A对集合使用Iterator迭代遍历,线程B则对集合进行增删操作。线程A、B一旦交替运行,就会出现在迭代的同时对集合增删的效果,也会抛出异常。解决办法就是加锁变成原子操作,多线程在这里不是本文重点,不多说了。

2. 集合中的for-Each循环能代替集合的普通for循环吗?

同样也是不能的。集合中的for-Each循环的局限性与数组的for-Each循环是一样的。集合的for-Each循环是不能对集合进行增删操作、也不能获取索引。而集合的普通for循环可以使用的迭代器提供了对集合的增删方法(如:Iterator.removeListIterator.add()),获取索引的方法(如:ListIterator.nextIndex()ListIterator.previousIndex());

三、Iterator源码分析

我们来分析一下Iterator源码,主要看看为什么在集合迭代时,修改集合可能会抛出ConcurrentModificationException异常。以ArrayList中实现的Iterator为例。

先来看一下ArrayList.iterator()方法,如下:

复制代码
1
2
3
4
public Iterator<E> iterator() { return new Itr(); }

iterator()方法直接创建了一个类Itr的对象。那就接着看 Itr类的定义吧!发现Itr其实是ArrayList的内部类,实现了 Iterator 接口。

复制代码
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator<E> { int cursor; // 当前的索引值,index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); //ArrayList的底层数组 Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; //再次更新 expectedModCount expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } @Override @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); final int size = ArrayList.this.size; int i = cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } }

ArrayList.this.elementDataArrayList的底层数组,上面这些方法都很简单,都是对ArrayList.this.elementData这个底层数组进行操作。
  重点看一下checkForComodification()方法,这个方法就是用来抛出 ConcurrentModificationException异常,这个方法也很简单,就是判断modCountexpectedModCount是否相等。modCount存储的AarryList中的元素个数。而expectedModCount则是对象创建时将modCount的值赋给它,也就是说expectedModCount存储的是迭代器创建时元素的个数。那么checkForComodification()方法其实在比较迭代期间,ArrayList元素的个数 是否发生了改变,如果改变了,就抛出异常。注意一下,expectedModCount除了在声明时赋值外,也在remove()方法中更新了一次。

总结

  • 无论是在数组中还是在集合中,for-Each加强型for循环都是它们各自的普通for循环的一种“简写方式”,即两者意思上是等价的,但前者方便简单,建议多使用。
  • for-Each循环不能完全代替普通for循环,因为for-Each有一定的局限性。
  • for-Each循环只能用于 数组、Iterable类型(包括集合)。
  • 集合中的for-Each循环本质上使用了Ierator迭代器,所以要注意Itrator迭代陷阱(单线程和多线程都有问题)。

作者:jinggod
出处:http://www.cnblogs.com/jinggod/p/8424868.html

最后

以上就是奋斗花卷最近收集整理的关于java基础篇(4)加强型for循环与Iterator的全部内容,更多相关java基础篇(4)加强型for循环与Iterator内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(105)

评论列表共有 0 条评论

立即
投稿
返回
顶部