-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathNestedIteration.java
More file actions
59 lines (49 loc) · 1.37 KB
/
NestedIteration.java
File metadata and controls
59 lines (49 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Can you spot the bug? - Page 46
package effectivejava.chapter8.item46;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
enum Suit {
CLUB, DIAMOND, HEART, SPADE
}
enum Rank {
ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING
}
class Card {
final Suit suit;
final Rank rank;
Card(Suit suit, Rank rank) {
this.suit = suit;
this.rank = rank;
}
}
public class NestedIteration {
public static void wrong(){
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();){
Suit x = i.next();Rank y = j.next();
System.out.println(x + ":" + y);
deck.add(new Card(x, y));
}
}
public static void right(){
Collection<Suit> suits = Arrays.asList(Suit.values());
Collection<Rank> ranks = Arrays.asList(Rank.values());
List<Card> deck = new ArrayList<Card>();
// Preferred idiom for nested iteration on collections and arrays
for (Suit suit : suits)
for (Rank rank : ranks){
System.out.println(suit + ":" + rank);
deck.add(new Card(suit, rank));
}
}
public static void main(String[] args) {
//wrong();
right();
}
}