OnJava8-Examples/typeinfo/PetCount.java

66 lines
1.9 KiB
Java
Raw Normal View History

2015-09-07 11:44:36 -06:00
// typeinfo/PetCount.java
2016-12-30 17:23:13 -08:00
// (c)2017 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2016-01-25 18:05:55 -08:00
// Using instanceof
2015-06-15 17:47:35 -07:00
import typeinfo.pets.*;
import java.util.*;
public class PetCount {
2015-12-15 11:47:04 -08:00
static class Counter extends HashMap<String,Integer> {
2015-06-15 17:47:35 -07:00
public void count(String type) {
Integer quantity = get(type);
if(quantity == null)
put(type, 1);
else
put(type, quantity + 1);
}
}
public static void
countPets(PetCreator creator) {
2015-12-15 11:47:04 -08:00
Counter counter = new Counter();
for(Pet pet : Pets.array(20)) {
2015-06-15 17:47:35 -07:00
// List each individual pet:
2015-12-02 09:20:27 -08:00
System.out.print(
pet.getClass().getSimpleName() + " ");
2015-06-15 17:47:35 -07:00
if(pet instanceof Pet)
counter.count("Pet");
if(pet instanceof Dog)
counter.count("Dog");
if(pet instanceof Mutt)
counter.count("Mutt");
if(pet instanceof Pug)
counter.count("Pug");
if(pet instanceof Cat)
counter.count("Cat");
if(pet instanceof EgyptianMau)
counter.count("EgyptianMau");
if(pet instanceof Manx)
counter.count("Manx");
if(pet instanceof Cymric)
counter.count("Cymric");
if(pet instanceof Rodent)
counter.count("Rodent");
if(pet instanceof Rat)
counter.count("Rat");
if(pet instanceof Mouse)
counter.count("Mouse");
if(pet instanceof Hamster)
counter.count("Hamster");
}
// Show the counts:
2015-11-03 12:00:44 -08:00
System.out.println();
System.out.println(counter);
2015-06-15 17:47:35 -07:00
}
public static void main(String[] args) {
countPets(new ForNameCreator());
}
2015-09-07 11:44:36 -06:00
}
/* Output:
2015-06-15 17:47:35 -07:00
Rat Manx Cymric Mutt Pug Cymric Pug Manx Cymric Rat
EgyptianMau Hamster EgyptianMau Mutt Mutt Cymric Mouse Pug
Mouse Cymric
{EgyptianMau=2, Pug=3, Rat=2, Cymric=5, Mouse=2, Cat=9,
Manx=7, Rodent=5, Mutt=3, Dog=6, Pet=20, Hamster=1}
2015-09-07 11:44:36 -06:00
*/