Type conversion

styrofoam fly

I have

private HashMap<Key<?>, Val<?>> myMap;

In this map under a specified key<T> is always val<T> (the same T). I want to make a function that uses this information and automatically gives me a value converted to given type. Is it possible? Something like this:

public class MyClass{
    private HashMap<Key<?>, Val<?>> myMap;
    public Val<T> getValue(Key<T> key) {
        return (Val<T>) myMap.get(key) 
    }

(Type T is not given in the class.)

ekj

There are two possible solutions to this:

  1. Define the generic type on the method:

    public class MyClass{
        private HashMap<Key<?>, Val<?>> myMap;
        public <T> Val<T> getValue(Key<T> key){
            return (Val<T>) myMap.get(key) 
        }
    
  2. Define the generic type on the class:

    public class MyClass<T> {
        private HashMap<Key<?>, Val<?>> myMap;
        public Val<T> getValue(Key<T> key) {
           return (Val<T>) myMap.get(key);
        }
    }
    

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related