import java.util.*;

public class Favorites {
    // Typesafe heterogeneous container pattern - implementation
    private Map<Class<?>, Object> favorites =
        new HashMap<Class<?>, Object>();

    public <T> void putFavorite(Class<T> type, T instance) {
        if (type == null)
            throw new NullPointerException("Type is null");
        favorites.put(type, instance);
    }

    public <T> T getFavorite(Class<T> 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));
    }
}

相关文章:

  • 2021-10-15
  • 2021-08-21
  • 2021-08-31
  • 2022-12-23
  • 2022-01-24
  • 2022-12-23
猜你喜欢
  • 2021-10-04
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2018-05-02
  • 2021-11-11
相关资源
相似解决方案