Java Collection How to - Create String to super class type mapping








Question

We would like to know how to create String to super class type mapping.

Answer

import java.util.HashMap;
import java.util.Map;
/*from   ww  w .  java 2  s .c om*/
class Pizza {
}

class CheesePizza extends Pizza {
}

class VeggiePizza extends Pizza {
}

public class Main {

  public static void main(String... args) {
    Map<String, Pizza> pizzaStock = new HashMap<String, Pizza>();

    pizzaStock.put("cheese", new CheesePizza());
    pizzaStock.put("veggie", new VeggiePizza());
    System.out.println(pizzaStock);
  }
}

The code above generates the following result.