For-each takes precedence over traditional for or while

For-each takes precedence over traditional for or while
Before Java 1.5, a collection must be looped.

for (Iterator i = c.iterator(); i.hasNext(); ) {
  doSomething((Element) i.next()); // (No generics before 1.5)
}
The loop array is like this

for (int i = 0; i < a.length; i++) {
  doSomething(a[i]);
}
These practices are better than while, but there are still too many places you may change to your index variable or iterator

So the recommended way in this book is as follows

for (Element e : elements) {
  doSomething(e);
}
The colon stands for each element e in the set

Not only is it the same in performance (even better), it wo n’t give you a chance to write bugs

The author also gave an example of wanting to print each card of a deck

enum Suit { CLUB, DIAMOND, HEART, SPADE }
enum Rank { ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT,
NINE, TEN, JACK, QUEEN, KING }
Collection<Suit> suits = Arrays.asList(Suit.values());
Collection<Rank> ranks = Arrays.asList(Rank.values());
List<Card> deck = new ArrayList<Card>();
for (Iterator<Suit> i = suits.iterator(); i.hasNext(); ){
  for (Iterator<Rank> j = ranks.iterator(); j.hasNext(); ){
    deck.add(new Card(i.next(), j.next()));
  }
}
The reason is also very simple is that the two iterators learn the method together to temporarily store the external value

It ’s really ugly and easy to have bugs. If you use for-each

for (Suit suit : suits){
  for (Rank rank : ranks){
    deck.add(new Card(suit, rank));
  }
}
Simply elegant

Iterable

For what kind of category can you use for-each? The answer is that the category must implement Iterable

public interface Iterable<E> {
  //Returns an iterator over the elements in this iterable
  Iterator<E> iterator()
}

Exception

Basically, as long as the category you want to loop has Iterable implemented, you should use for-each

1. Same performance

2. Prevent bugs

3. Simple program

But there are three situations where you cannot use for-each

1. Filter or delete: To delete something, you must use an iterator (because you may need to call remove ())

2. Conversion: is to change the value for-each can only be used to read elements

3. Parallel iteration: when the bug just turned into a feature, when you really want the index or iterator of the inner and outer loops to advance together

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation