Casting Map <Integer,Set <Object >>

Lui*_*Sep 7 java casting

我有一个带Map<Integer, Set<Object>>参数的方法.我需要使用a Map<Integer, Set<String>>和a Map<Integer, Set<Integer>>参数从两个不同的位置调用它.

编译器投诉所以我改变了方法参数签名Map<Integer, ?>,现在我可以调用它,但是有不同的问题.方法基本如下:

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>)
    }
Run Code Online (Sandbox Code Playgroud)

有没有办法解决编译错误?这是,铸造list?.

我的第二个问题是概念性的 除了使用不同的参数签名编写两种不同的方法之外,还有更好的方法吗?

san*_*hat 7

声明为

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); 
    }
Run Code Online (Sandbox Code Playgroud)

当你试图使用多种类型的参数时,使用泛型总是好的,而不是使用Object?(未知类型)

现在,您可以使用Setcontainsig不同类型调用相同的方法,如下所示

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);
Run Code Online (Sandbox Code Playgroud)