Blog信息 |
blog名称: 日志总数:1304 评论数量:2242 留言数量:5 访问次数:7617055 建立时间:2006年5月29日 |

| |
[J2SE]For-Each 循环 软件技术
lhwork 发表于 2006/8/21 10:04:41 |
管中窥虎
在学习
java 1.5
的过程中,我使用了
sun
公布的
tutorial
,这份文档写的比较详尽易明,但是对于想快速了解
tiger
而且具有较好
java
基础的人来说,大篇幅的英文文档是比较耗时间和非必需的,所以我将会归纳这份文档的主要内容,在保证理解的底线上,尽力减少阅读者需要的时间。
在以下地址可以进入各新增语言特色介绍以及下载相关文档(若有)。
http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html
第二道虎纹:
For-Each
循环
目前在一个容器里做迭代访问挺郁闷的,看看下面这个方法,方法的目的是把容器里的一系列计时任务取消。
500)this.width=500'>
500)this.width=500'>
void
cancelAll(Collection
<
TimerTask
>
c)
500)this.width=500'>
{500)this.width=500'>500)this.width=500'>
for
(Iterator
<
TimerTask
>
i
=
c.iterator(); i.hasNext(); )500)this.width=500'>500)this.width=500'> i.next().cancel();500)this.width=500'>500)this.width=500'>}
500)this.width=500'>
关于
Iterator
的部分真的很罗嗦,而且容易出错。现在再看看
1.5
里带来的
For-each
循环:
void
cancelAll(Collection
<
TimerTask
>
c) {
for
(TimerTask t : c) t.cancel();}
这个新的循环和泛型完美配合,既保持类型安全,又去掉了冗余。
以下是一个在试图嵌套迭代的时候经常会犯的错误。
List suits
=
500)this.width=500'>;List ranks
=
500)this.width=500'>;List sortedDeck
=
new
ArrayList();
//
BROKEN - throws NoSuchElementException!
for
(Iterator i
=
suits.iterator(); i.hasNext(); )
for
(Iterator j
=
ranks.iterator(); j.hasNext(); ) sortedDeck.add(
new
Card(i.next(), j.next()));
原因是
i.next()
被过多的调用了。
再看看新循环的表现,简直是度身定造一样的般配。
for
(Suit suit : suits)
for
(Rank rank : ranks) sortedDeck.add(
new
Card(suit, rank));
for-each
循环也适用于数组,象隐藏迭代子一样,这次它把数组下标藏起来了。
500)this.width=500'>
//
Returns the sum of the elements of a
500)this.width=500'>
500)this.width=500'>
500)this.width=500'>
int
sum(
int
[] a)
500)this.width=500'>
{500)this.width=500'>500)this.width=500'>
int
result
=
0
;500)this.width=500'>500)this.width=500'>
for
(
int
i : a)500)this.width=500'>500)this.width=500'> result
+=
i;500)this.width=500'>500)this.width=500'>
return
result;500)this.width=500'>500)this.width=500'>}
500)this.width=500'>
那么我们什么时候该用
for-each
循环呢?只要情况运行就应该用,它真的让你的代码好看了很多。不幸的是,它有不能发挥作用的情形,就是需要用
iterator
的
remove
方法的时候,因为
iterator
被隐藏了,你也无法调用它的方法了,新的循环不适用于过滤元素。同样的也不适用于需要把数组中的元素替换掉的情况。最后,它也不能在平行遍历多个容器的情况里使用,这些缺点,设计者是知道的,但是最后他们明智地选择这样一个简单的,能适用于多数情况的设计方案
|
|
|