Use for-each liberally

http://www.javapractices.com/topic/TopicAction.do?Id=196


The for-each loop is used with both collections and arrays. It's intended to simplify the most common form of iteration, where the iterator or index is used solely for iteration, and not for any other kind of operation, such as removing or editing an item in the collection or array. When there is a choice, the for-each loop should be preferred over the for loop, since it increases legibility.

Example

Here are some examples of the for-each loop. 

import java.util.*;
import java.math.BigDecimal;

public final class ForEachExamples {

  public static void main(String... aArgs){
    List<Number> numbers = new ArrayList<>();
    numbers.add(new Integer(42));
    numbers.add(new Integer(-30));
    numbers.add(new BigDecimal("654.2"));

    //typical for-each loop
    //processes each item, without changing the collection or array.
    for (Number number : numbers){
      log(number);
    }

    //use with an array
    String[] names = {"Ethan Hawke", "Julie Delpy"};
    for(String name : names){
      log("Name : " + name);
    }

    //removal of items requires an explicit iterator,
    //so you can't use a for-each loop in this case
    Collection<String> words = new ArrayList<>();
    words.add("Il ne lui faut que deux choses: ");
    words.add("le");
    words.add("pain");
    words.add("et");
    words.add("le");
    words.add("temps.");
    words.add("- Alfred de Vigny.");
    for(Iterator<String> iter = words.iterator(); iter.hasNext();){
      if (iter.next().length() == 4){
        iter.remove();
      }
    }
    log("Edited words: " + words.toString());

    //if used with a non-parameterized type (not recommended), 
    //then Object must be used, along with a cast
    Collection stuff = new ArrayList();
    stuff.add("blah");
    for (Object thing : stuff){
      String item = (String)thing;
      log("Thing : " + item);
    }
  }

  // PRIVATE
  private static void log(Object aThing){
    System.out.println(aThing);
  }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值