[英]The way to instantiate map<String, List<String>> in Java
I would like to instantiate Map<String, List<String>>
in Java, 我想在Java中实例化
Map<String, List<String>>
,
I tried 我试过了
Map<String, List<String>> foo = new <String, List<String>>();
and 和
Map<String, List<String>> foo = new <String, ArrayList<String>>();
None of them work. 他们都没有工作。 Does any one know how to instantiate this map in Java?
有没有人知道如何在Java中实例化这个地图?
new HashMap<String, List<String>>();
or as gparyani commented: 或者像gparyani评论的那样:
new HashMap<>(); // type inference
Note: each entry needs to be given an instantiated List as a value. 注意:每个条目都需要以实例化的List作为值。 You cannot get("myKey").add("some_string_for_this_key");
你不能得到(“myKey”)。add(“some_string_for_this_key”); the very first time you get() a List from it.
你第一次从中得到一个List。
So, fetch a List, check if it's null. 因此,获取一个List,检查它是否为null。
If it's null, make a new list, add the string to it, put the List back. 如果它为null,则创建一个新列表,将字符串添加到其中,然后将List放回。 If it's anything but null, add to it, or do what you want.
如果它只是null,添加到它,或做你想要的。
You forgot to mention the class. 你忘了提这堂课。
Map
here is the reference type and is an Interface . 这里的
Map
是引用类型,是一个接口 。 HashMap
on the other side of equals specifies the actual type of the Object created and assigned to the reference foo
. equals另一侧的
HashMap
指定创建并分配给引用foo
的Object的实际类型。
Map<String, List<String>> foo = new HashMap<String, List<String>>();
The actual type specified ( HashMap
here) must be assignable to the reference type ( Map
here) ie if the type of reference is an Interface , the Object's type must implement it. 指定的实际类型(此处为
HashMap
)必须可分配给引用类型(此处为Map
),即如果引用类型是接口 ,则Object的类型必须实现它。 And, if the type of the reference is a Class , the Object's type must either be the same class or its subtype ie it extends from it. 并且,如果引用的类型是Class ,则Object的类型必须是相同的类或其子类型,即它从它延伸。
From Java 7 onwards, you can use a shorthand like 从Java 7开始,您可以使用类似的简写
Map<String, List<String>> foo = new HashMap<>();
Your second way of instantiation is not recommended. 不推荐您的第二种实例化方法。 Stick to using
List
which is an Interface . 坚持使用
List
作为接口 。
// Don't bind your Map to ArrayList
new TreeMap<String, ArrayList<String>>();
// Use List interface type instead
new TreeMap<String, List<String>>();
Map is an interface. 地图是一个界面。 You have to tell Java which concrete Map class you want to instantiate.
您必须告诉Java要实例化哪个具体的Map类。
Map<String, List<String>> foo = new HashMap<String, List<String>>();
or 要么
Map<String, List<String>> foo = new TreeMap<String, List<String>>();
etc. 等等
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.