-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathPetCount3.java
More file actions
50 lines (43 loc) · 1.36 KB
/
PetCount3.java
File metadata and controls
50 lines (43 loc) · 1.36 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
//: typeinfo/PetCount3.java
// Using isInstance()
package thinkinginjava.typeinfo;
import java.util.LinkedHashMap;
import java.util.Map;
import thinkinginjava.typeinfo.pets.LiteralPetCreator;
import thinkinginjava.typeinfo.pets.Pet;
import thinkinginjava.typeinfo.pets.Pets;
public class PetCount3 {
static class PetCounter extends
LinkedHashMap<Class<? extends Pet>, Integer> {
public PetCounter() {
super(MapData.map(LiteralPetCreator.allTypes, 0));
}
public void count(Pet pet) {
// Class.isInstance() eliminates instanceofs:
for (Map.Entry<Class<? extends Pet>, Integer> pair : entrySet())
if (pair.getKey().isInstance(pet))
put(pair.getKey(), pair.getValue() + 1);
}
public String toString() {
StringBuilder result = new StringBuilder("{");
for (Map.Entry<Class<? extends Pet>, Integer> pair : entrySet()) {
result.append(pair.getKey().getSimpleName());
result.append("=");
result.append(pair.getValue());
result.append(", ");
}
result.delete(result.length() - 2, result.length());
result.append("}");
return result.toString();
}
}
public static void main(String[] args) {
PetCounter petCount = new PetCounter();
for (Pet pet : Pets.createArray(20)) {
System.out.println((pet.getClass().getSimpleName() + " "));
petCount.count(pet);
}
System.out.println();
System.out.println(petCount);
}
}