java - 转换 Map<Integer, Set<Object>>

标签 java casting

我有一个采用 Map<Integer, Set<Object>> 的方法作为参数。我需要使用 Map<Integer, Set<String>> 从两个不同的位置调用它和一个 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>)
    }

有什么办法可以解决编译错误吗?这是,类型转换 list? .

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

最佳答案

声明为

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); 
    }

当您尝试使用多种类型的参数时,使用泛型总是比使用Object?(未知类型)好

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

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);

关于java - 转换 Map<Integer, Set<Object>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16357328/

相关文章:

java - 将 double(原始)转换为 Long(包装)

c++ - 如何解决此 "cast to pointer from type of different size"警告?

java - 每次单击时创建包含 JTextField、JComboBox 和 JButton 的新行

java - 在类中使用共享服务

Java Stream API 将 lambda 表达式存储为变量

java - 二维数组网格 - 将字符放置在每个单元格的中间

c# - 为什么在声明中隐式向上转换?

iOS 转换为 BOOL

c++ - Catch2 强制我将 std::string 的强制转换添加到我的异常中,这会产生其他问题吗?

java - TableViewer 和 TreeViewer 的混合版本