简体   繁体   中英

How do I return a defined Map?

I want to define a function which returns an instantiated map depending on the Key and Value class which I give it:

something like

Map<Integer, String> map = getMap(Integer.class, String.class);

but I am unsure how to define the getMap function in the correct way. I was thinking something like

<K,V> Map<K,V> getMap(Class<K> keyClass, Class<V> valClass) {
   Map<keyClass, valClass> retMap = new HashMap<keyClass, valClass);


   .... // add values to my map

   return retMap;
}

But this doesn't seem to work at all.

does anyone have any suggestions?

You are mixing the concepts. Map is a generic type. Generics in Java will be erased upon compilation. So you cannot set them in runtime as you did. The correct way could be like this:

static <K,V> Map<K,V> getMap() { return new HashMap<K, V>(); }

Then you can invoke it like:

Map<Integer, String> m = getMap();

The proper syntax is much simpler:

Map<K, V> retMap = new HashMap<K, V>();

Because K and V are the type placeholders. The Class<K> and Class<V> variables are not needed here; but you will need them so the compiler can infer the proper types on invocation.

You did it too complicated, but you are really close. This way you will sort it out:

    <K,V> Map<K,V> getMap() {
           Map<K, V> retMap = new HashMap<K, V>();
           // add entries into the map
           return retMap;
    }

Java has a pretty nice automatic type inference for generic methods.

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