简体   繁体   中英

A generic question about heterogeneous container?

I'm learning the effective java, I found a question for heterogeneous container. When I set a value into heterogeneous container, IDEA IDE give me a error:

'putFavorite(java.lang.Class<capture<? extends java.lang.String>>, capture<? extends java.lang.String>)' in 'com.kai.java.Favorites' 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 will have to change the signatur of putFavorite to

public <T> void putFavorite(Class<? extends T> type, T instance)

Note the use of ? extends T ? extends T instead of just T .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM