"Java Alley"
by  Bruce Eckel
Web Techniques,  March 1997

Web Techniques grants permission to use these listings for private or 
commercial use provided that credit to Web Techniques and the author is 
maintained within the comments of the source. For questions, contact
editors@web-techniques.com.


[LISTING ONE]

//: PetCount.java
/**
 * Using instanceof
 */
import java.util.*;

class pet {}
class dog extends pet {}
class pug extends dog {}
class cat extends pet {}
class rodent extends pet {}
class gerbil extends rodent {}
class hamster extends rodent {}

class counter { int i; }

public class PetCount {
  static String[] typenames = {
    "pet", "dog", "pug", "cat",
    "rodent", "gerbil", "hamster",
  };
  public static void main(String args[]) {
    Vector pets = new Vector();
    try {
      Class[] PetTypes = {
        Class.forName("dog"),
        Class.forName("pug"),
        Class.forName("cat"),
        Class.forName("rodent"),
        Class.forName("gerbil"),
        Class.forName("hamster"),
      };
      for(int i = 0; i < 15; i++)
        pets.addElement(
          PetTypes[
            (int)(Math.random() * PetTypes.length)]
            .newInstance()
        );
    } catch(InstantiationException e) {}
      catch(IllegalAccessException e) {}
      catch(ClassNotFoundException e) {}
    Hashtable h = new Hashtable();
    for(int i = 0; i < typenames.length; i++)
      h.put(typenames[i], new counter());
    for(int i = 0; i < pets.size(); i++) {
      Object o = pets.elementAt(i);
      if(o instanceof pet)
        ((counter)h.get("pet")).i++;
      if(o instanceof dog)
        ((counter)h.get("dog")).i++;
      if(o instanceof pug)
        ((counter)h.get("pug")).i++;
      if(o instanceof cat)
        ((counter)h.get("cat")).i++;
      if(o instanceof rodent)
        ((counter)h.get("rodent")).i++;
      if(o instanceof gerbil)
        ((counter)h.get("gerbil")).i++;
      if(o instanceof hamster)
        ((counter)h.get("hamster")).i++;
    }
    System.out.println("pets = ");
    for(int i = 0; i < pets.size(); i++)
      System.out.println(
        pets.elementAt(i).getClass().toString());
    System.out.println("h = ");
    for(int i = 0; i < typenames.length; i++)
      System.out.println(
        typenames[i] + " quantity: " +
        ((counter)h.get(typenames[i])).i
      );
  }
}