Java – General Questions About Heterogeneous Containers?

General Questions About Heterogeneous Containers?… here is a solution to the problem.

General Questions About Heterogeneous Containers?

I’m learning effective java and I found a question about heterogeneous containers. When I set a value in a heterogeneous container, the IDEA IDE reports an error:

'putFavorite(java.lang.Class<capture<? extends java.lang.String>>, capture<? extends java.lang.String>)' in '' cannot be applied to '(java.lang.Class<capture<? extends java.lang.String>>, java.lang.String)'

My code:

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class App {
    public static void main(String[] args) {
        Favorites favorites = new Favorites();
        favorites.putFavorite(String.class, "12345");
        favorites.putFavorite(String.class, "5678");
        favorites.putFavorite("123".getClass(), "999999");  error

class Favorites {
    private Map<Class<?>, Object> favorites = new HashMap<>();

public <T> void putFavorite(Class<T> type, T instance) {
        favorites.put(Objects.requireNonNull(type), instance);

public <T> T getFavorite(Class<T> type) {
        return type.cast(favorites.get(type));


You must change putFavorite's signature to

<pre class=”lang-java prettyprint-override”>public <T> void putFavorite(Class<? extends T> type, T instance)

Please note the use of ? Extend T and not just T.

Related Problems and Solutions