0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Item 58: Prefer for-each loops to traditional for loops

Posted at

58.従来のforループより、for-eachのループを選択すべき

  • 従来のfor文のほうが記述すべきことが多くて、ミスが発生する確率が上がる。
  • 入れ子のイテレーションがあるときもfor-eachが使える。
package tryAny.effectiveJava;

import java.util.Arrays;
import java.util.Collection;

public class NestedFor {
    enum Suit {
        CLUB, DIAMOND, HEART, SPADE
    };

    enum Rank {
        ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING
    };

    public static void main(String[] args) {
        Collection<Suit> suits = Arrays.asList(Suit.values());
        Collection<Rank> ranks = Arrays.asList(Rank.values());

        for (Suit suit : suits) {
            for (Rank rank : ranks) {
                System.out.println("柄" + suit + ":数" + rank);
            }
        }
    }
}
  • 一般的にfor-eachが使えない場面が3つある。

    • フィルタリングして特定の要素を削除する場合

    • 要素の値を変換する場合

    • 複数の要素集合を、並列で走査する場合

  • Iterableをimplementsしているオブジェクトに対してfor-eachで要素を取り出すことができる。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?