java中foreach的使用
Java5之后新增了foreach语法,可以看成for循环的一个扩展,其主要用处在于使得遍历数组或者其他集合(collections)更为方便。这个新语法命名为enhanced for或者foreeach(参考其他语言的命名方式)。
foreach可用于遍历数组和Collections中每一个连续的值。当然它也可以用于遍历那些已经实现了Iterable<E> 的接口的对象(需要定义iterator()函数),而许多Collections类都已经实现了Iterable<E>,这使得 foreach语法用了用武之地。
通用格式
以下列出foreach和for的使用形式,同时给出两个基本的对等式,区别在于是数组还是其他可迭代对象。
例子-计算数组中各元素和
foreach语法实现:
1
2
3
4
5
|
double
[] ar = {
1.2
,
3.0
,
0.8
};
int
sum =
0
;
for
(
double
d : ar) {
// d gets successively each value in ar.
sum += d;
}
|
for语法的实现:
1
2
3
4
5
|
double
[] ar = {
1.2
,
3.0
,
0.8
};
int
sum =
0
;
for
(
int
i =
0
; i < ar.length; i++) {
// i indexes each element successively.
sum += ar[i];
}
|
何时使用foreach合适
从上方例子中可以看出,foreach有些时候能够使得代码变得干净,但是需要注意某些情况写不合适:
- 只读:访问的元素不能被赋值,比如元素的自增等
- 单一结构:不可能同时遍历两个结构,比如比较两个数组
- 单一元素:只适合单一的元素读取
- 单向:只能向前单个元素的迭代
- 需java5支持:不要在java5前使用该语法
二维数组中foreach的使用
举例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public
class
test02 {
public
static
void
main(String args[])
{
int
[][] a =
new
int
[][] {
{
1
,
2
,
3
,
4
,
5
},
{
10
,
11
,
12
}
};
for
(
int
[] row : a) {
for
(
int
element : row)
System.out.print(element +
" "
);
System.out.println();
}
}
}
|
foreach更多运用
前面已经说了foreach适用于遍历数组或者Collections等实现了Iterable<T>接口的对象。例如遍历List或者Set:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
//List
public
void
go(List<String> list) {
for
(String element : list) {
System.out.println(element);
}
}
//set
public
void
go(Set<String> set) {
for
(String element : set) {
System.out.println(element);
}
}
|
Collections的遍历如下:
1
2
3
4
5
|
public
void
go(Collection<String> collection) {
for
(String element : collection) {
System.out.println(element);
}
}
|
其实在编译的时候,编译器会把foreach展开,比如上面的Collections展开如下:
1
2
3
4
5
6
|
public
void
go(Collection collection) {
String s;
for
(Iterator iterator = collection.iterator();
iterator.hasNext(); System.out.println(s))
s = (String)iterator.next();
}
|
转载自: http://www.leyond.info/usage-of-foreach-in-java/#more-131521
更多关于foreach的神秘资料,
参考:http://caterpillar.onlyfun.net/Gossip/JavaEssence/Foreach.html ,本文还参考了: