增强for循环

l语法:
Øfor ( type 变量名:集合变量名 )  { … }
l注意事项:
Ø迭代变量必须在( )中定义!
Ø集合变量可以是数组或实现了Iterable接口的集合类
l举例:

  public static int add(int x,int ...args) {

  int sum = x;

  for(int arg:args) {

  sum += arg;

  }

  return sum;

  }


The enhanced for statement has the form:
EnhancedForStatement:
for ( Var iableModi f ie rsopt 
Type Identifier: Expression) Statement
The Expression must either have type Iterable or else it must be of an array
type (§10.1), or a compile-time error occurs.
The scope of a local variable declared in the  FormalParameter part of an
enhanced for statement (§14.14) is the contained Statement
The meaning of the enhanced  for statement is given by translation into a
basic for statement. 
If the type of Expression is a subtype of Iterable, then let I be the type of the
expression Expression.iterator(). The enhanced for statement is equivalent to
a basic for statement of the form:
for (I #i = Expression.iterator(); #i.hasNext(); ) {
VariableModifiersopt Type Identifier = #i.next();
Statement
}

Where #i is a compiler-generated identifier that is distinct from any other identifi-
ers (compiler-generated or otherwise) that are in scope (§6.3) at the point where
the enhanced for statement occurs.
Otherwise, the Expression necessarily has an array type, T[]. Let L1 ... Lm
be the (possibly empty) sequence of labels immediately preceding the enhanced
for statement. Then the meaning of the enhanced for statement is given by the
following basic for statement:
T[] a = Expression;
L1: L2: ... Lm:
for (int i = 0; i < a.length; i++) {
VariableModifiersopt 
Type Identifier = a[i];
Statement
}


Where a and i are compiler-generated identifiers that are distinct from any other
identifiers (compiler-generated or otherwise) that are in scope at the point where
the enhanced for statement occurs.


DISCUSSION
The following example, which calculates the sum of an integer array, shows how enhanced
for works for arrays: 
    int sum(int[] a) {
        int sum = 0;
        for (int i : a)
            sum += i;
        return sum;
    }
Here is an example that combines the enhanced for statement with auto-unboxing to trans-
late a histogram into a frequency table:
    Map<String, Integer> histogram = ...;
    double total = 0;
    for (int i : histogram.values())
        total += i;
    for (Map.Entry<String, Integer> e : histogram.entrySet())
        System.out.println(e.getKey() + "" + e.getValue() / total);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值