Pankaj
Pankaj

Reputation: 3674

Change Map of Map to generic type

I have a method which takes a Map which has Key as String and value as an object of type T which is a serializable object.

public <T extends Serializable> void set(String key, Map<String, T> fields) {
  ......
  .......
}

When I'm trying to pass map of map, it's giving an error for wrong argument type. I want this method to take a generic object and don't want to change it to set(String key, Map<String, Map<String, String>> fields)

Map<String, String> fieldmapL1 = new HashMap<>();
fieldmapL1.put("ABC", "XYZ");
Map<String, Map<String, String>> fieldmapL2 = new HashMap<>();
fieldmapL2.put("Key", fieldmapL1);

instance.set("key", fieldmapL2);

enter image description here

Upvotes: 0

Views: 1227

Answers (2)

Wisthler
Wisthler

Reputation: 587

You issue is that you type is not matching you requirements. As explained by @Pankaj in others comments of this topic, Map is not serializable so your definition of fieldmap2 does not meet the criteria for T. Updating instantiations of maps to properly use HashMap which implements serializable do the trick (aka no more warning in intelliJ)

public static class Test{
        public <T extends Serializable> void set(String key, Map<String, T> fields) {

        }
    }


    public static void main(String[] args) {
        HashMap<String, String> fieldMapL1 = new HashMap<>();
        fieldMapL1.put("ABC", "XYZ");
        Map<String, HashMap<String, String>> fieldmap2 = new HashMap<>();
        fieldmap2.put("key", fieldMapL1);

        Test test = new Test();
        test.set("key", fieldmap2);
    }

Upvotes: 2

Andronicus
Andronicus

Reputation: 26076

You need to indicate the type, you're using:

instance.<Map<String, String>>set("key", fieldmapL2);

Then type T is resolved to String. Also this will work only if instance is properly instantiated (you can set T to String on instantiation, then you don't need the above line or you can omit explicit types and use my solution).

Upvotes: 3

Related Questions