简体   繁体   English

HashMap / TreeSet组合不一致

[英]HashMap / TreeSet combination inconsistency

This works ok: 这样可行:

Map aMap;
aMap = new HashMap<String, TreeSet<String>>();

This does not compile: 这不编译:

Map<String, Set<String>> aMap;
aMap = new HashMap<String, TreeSet<String>>();

Error message: 错误信息:

Compilation failed (26/05/2014 11:45:43) Error: line 2 - incompatible types - 
  found java.util.HashMap<java.lang.String,java.util.TreeSet<java.lang.String>>
  but expected java.util.Map<java.lang.String,java.util.Set<java.lang.String>>

Why? 为什么?

The first one works because you use a raw type (without generic) so you can put any type of map in there. 第一个可行,因为您使用原始类型(没有通用),因此您可以在其中放置任何类型的地图。

The second one doesn't work because a XXX<Set> is not a XXX<TreeSet> . 第二个不起作用,因为XXX<Set>不是XXX<TreeSet>

So you need to choose between: 所以你需要选择:

Map<String, Set<String>> aMap = new HashMap<String, Set<String>>();
//or
Map<String, TreeSet<String>> aMap = new HashMap<String, TreeSet<String>>();

And in both case you will be able to write: 在这两种情况下,您都可以写:

aMap.put("abc", new TreeSet<>());

The main difference is when you get an item from the map, with the former construct you won't have access to the TreeSet specific methods. 主要区别在于从地图中获取项目时,使用前一个构造,您将无法访问TreeSet特定方法。

Finally, with Java 7+ you can omit the generic information on the right hand side and the compiler will determine it automatically for you: 最后,使用Java 7+,您可以省略右侧的通用信息,编译器将自动为您确定:

Map<String, Set<String>> aMap = new HashMap<>();
Map<String, TreeSet<String>> aMap = new HashMap<>();

Use this instead: 请改用:

    Map<String, ? extends Set<String>> aMap;
    aMap = new HashMap<String, TreeSet<String>>();

Because the Set's generic must not be the same than TreeSet's generic. 因为Set的泛型不能与TreeSet的泛型相同。

在此输入图像描述

+1 to Peter's answer, TreeSet implements SortedSet which extends Set. 对于Peter的回答+1,TreeSet实现了扩展Set的SortedSet。

Map<String, ? extends Set<String>> aMap;
    aMap = new HashMap<String, TreeSet<String>>();

will work fine. 会很好的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM