简体   繁体   中英

Generic method to insert into hashmap using the Class as key

I'm trying to create a method that receives an object that extends Component and insert it into a map that uses the objects class as key to the object itself. For some reason it is complaining about the put call

components = new Array<ObjectMap<Class,? extends Component>>();

public <T extends Component> void putComponentOnEntity(Entity e, T component) {
    if (entities.items[e.id] == null) {
        throw new IllegalArgumentException("Entity does not exist anymore");
    }
    ObjectMap<Class, ? extends Component> entityComponents = components.get(e.id);
    entityComponents.put(component.getClass(), component);
}

--

The method put(Class, capture#4-of ? extends Component) in the type ObjectMap<Class,capture#4-of ? extends Component> is not applicable for the arguments (Class<capture#5-of ? extends Component>, T)

You can't put anything (except null) inside a ObjectMap<Class, ? extends Component> ObjectMap<Class, ? extends Component> , because ObjectMap<Class, ? extends Component> ObjectMap<Class, ? extends Component> is a map of Class and of some unknown type which extends Component . So it could be an ObjectMap<Class, Label> or an ObjectMap<Class, Button> , but we don't know.

Adding any value to such a map would have a big chance of adding something which doesn't have the actual type of the values of the map (for example, a Label, when the map is a map of buttons), so the compiler forbids it.

The compiler must know the actual type hidden behind ? to check that what you add to the map is compatible with its type. That's what makes the generic types type-safe.

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