我遇到了如下场景:
Map1 - Map<String, Map<String,List<Vo>>>
Map2 - Map<String, Set<String>
是否可以为上述 2 个 map 设置相同的键引用,如下所示?
Map<String, Collection<?> mapCommon=new HashMap<String, Collection<?>();
谁能告诉我如何设置这个吗? 编辑:是的相同引用
最佳答案
您在这里触及了两个有趣的元素。
首先 - map 不属于 Collection 。 List 和 Set 确实属于同一类,但 Map 是不同的,尽管它与 List 和 Set 具有一些共同点。
其次 - 按照您尝试的方式将类型混合到一个 commonMap 中是可行的,但应该避免这样做,因为它通常不被认为是最佳实践。我们正在处理的问题是由类型删除引起的。一旦编译器编译了代码,它就不会传递有关 Map 或 Set 所持有的泛型类型的任何信息。有效地您的Map<String, List<Vo>>
变成原始类型Map<?>
在编译的代码中。这样做的问题是回溯原始值。如果实例是Map<String, List<Vo>>
,编译器将不允许您检查该实例。或Set<String>
。
以下代码将失败:
public static void processElement(Object commonMapObjectEitherMapOrSet) {
if (commonMapObjectEitherMapOrSet instanceof Map<String, List<Vo>>) {
//...
}
}
Error: Cannot perform instanceof check against parameterized type Map>. Use the form Map instead since further generic type information will be erased at runtime
可能的解决方法是忘记泛型并检查实例是否是原始类型 Set 或 Map。下面的代码显示了如何检查对象是 Map 还是 Set。
public static void processElement(Object commonMapObjectEitherMapOrSet) {
if (commonMapObjectEitherMapOrSet instanceof Map) {
System.out.println("Got map; but types held in the map are not known due to type-erasure");
// This is where things will get messy as you will get warnings:
Map<String, List<Vo>> map = (Map<String, List<Vo>>) commonMapObjectEitherMapOrSet;
// ...
}
if (commonMapObjectEitherMapOrSet instanceof Set) {
System.out.println("Got set; but types held in the set are not known due to type-erasure");
// This is where things will get messy as you will get warnings:
Set<String> set = (Set<String>) commonMapObjectEitherMapOrSet;
// ...
}
}
上述问题是将 commonMap 中的值转换回您想要的类型,即。 Map<String, List<Vo>>
和Set<String>
。编译器将无法检查转换是否正确,并会发出警告。从技术上讲,您可以使用(@SuppressWarnings("unchecked")
注释)抑制警告,但这可能不是最好的选择。
在这个阶段 - 考虑是否创建自己的专门类来管理不同类型是有意义的。 回到你原来的问题 - 为了回答它,我发布了将事物映射到通用 map 的代码:
package stackoverflow;
import java.util.*;
class Vo {}
public class MultipleRefs {
public static void main(String[] args) {
Map<String, List<Vo>> mapVo = new HashMap<>();
Set<String> set = new HashSet<>();
Map<String, Object> commonMap = new HashMap<>();
//commonMap.put("a", Map)
commonMap.put("mapVoOne", mapVo);
commonMap.put("setOne", set);
commonMap.forEach((key, value) -> processElement(value));
}
public static void processElement(Object commonMapObject) {
if (commonMapObject instanceof Map) {
System.out.println("Got map; but types held in the map are not known due to type-erasure");
// This is where things will get messy:
Map<String, List<Vo>> map = (Map<String, List<Vo>>) commonMapObject;
System.out.println(" processElement prints map: " + map);
}
if (commonMapObject instanceof Set) {
System.out.println("Got set; but types held in the set are not known due to type-erasure");
// This is where things will get messy:
Set<String> set = (Set<String>) commonMapObject;
System.out.println(" processElement prints set: " + set);
}
}
}
关于java - 在 map 中设置多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40180342/