import java.util.*;
public class Favorites {
// Typesafe heterogeneous container pattern - implementation
private Map, Object> favorites =
new HashMap, Object>();
public void putFavorite(Class type, T instance) {
if (type == null)
throw new NullPointerException("Type is null");
favorites.put(type, instance);
}
public T getFavorite(Class type) {
return type.cast(favorites.get(type));
}
// Typesafe heterogeneous container pattern - client
public static void main(String[] args) {
Favorites favorites = new Favorites();
favorites.putFavorite(String.class, "StringResult");
favorites.putFavorite(Integer.class, 12);
favorites.putFavorite(Boolean.class, false);
System.out.println("results are: "
+ favorites.getFavorite(String.class)
+ favorites.getFavorite(Integer.class)
+ favorites.getFavorite(Boolean.class));
}
}