Casting Map<Integer, Set<Object>>

casting, java

Solution

declare it as

private <T> void methodA (Map<Integer, Set<T>> inOutMap, Integer key, T value) {

        Set<T> list = new HashSet<T>();

        if (!inOutMap.containsKey(key)) {
            list.add(value);
        } else {
            list = inOutMap.get(key); 
            list.add(value);
        }

        inOutMap.put(key, list); 
    }

Its always good to use Generics when you are trying to use multiple types of arguments, than using `Object` or `?` (unknown type)

Now you can invoke the same method using `Set` containig different types like below

Map<Integer, Set<String>> m1 = new HashMap<Integer, Set<String>>();
Map<Integer, Set<Integer>> m2 = new HashMap<Integer, Set<Integer>>();

methodA(m1, 1, "t");
methodA(m2, 2, 2);

Problem

I have a method that takes a `Map<Integer, Set<Object>>` as parameter. I need to call it from two different locations, using a `Map<Integer, Set<String>>` and a `Map<Integer, Set<Integer>>` as parameter. The compiler complaint so I changed the method parameter signature to `Map<Integer, ?>`, and now I can call it, but have different problems. The method is basically as follows: ``` private void methodA (Map<Integer, ?> inOutMap, Integer key, Object value) { Set<Object> list = new HashSet<Object>(); if (!inOutMap.containsKey(key)) { list.add(value); } else { list = (Set<Object>) (Set<?>) inOutMap.get(key); //I wrote the cast, but looks quite ugly list.add(value); } inOutMap.put(key, list); //compiler error //The method put(Integer, capture#4-of ?) in the type Map<Integer,capture#4-of ?> is not applicable for the arguments (Integer, Set<Object>) } ``` Is there any way of solving the compiler error? This is, casting `list` to `?`. My second question is conceptual. Is there any better way of doing this besides writting two different methods with different parameters signature?

Original source