Ang*_*ker 8 java collections dictionary map
我需要在某些类型的集合中存储键/值信息.在C#中,我会定义一个这样的字典:
var entries = new Dictionary<string, int>();
entries.Add("Stop me", 11);
entries.Add("Feed me", 12);
entries.Add("Walk me", 13);
Run Code Online (Sandbox Code Playgroud)
然后我会访问这些值:
int value = entries["Stop me"];
Run Code Online (Sandbox Code Playgroud)
我如何用Java做到这一点?我已经看过了一些例子ArrayList,但如果可能的话,我想要使用泛型的解决方案.
oxb*_*kes 22
你想用一个 Map
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("Stop me", 11);
Integer i = m.get("Stop me"); // i == 11
Run Code Online (Sandbox Code Playgroud)
请注意,在最后一行,我可以说:
int i = m.get("Stop me");
Run Code Online (Sandbox Code Playgroud)
这是(使用Java的自动拆箱)的简写:
int i = m.get("Stop me").intValue()
Run Code Online (Sandbox Code Playgroud)
如果给定键的映射中没有值,则get返回null和此表达式将抛出一个NullPointerException.因此,在这种情况下使用盒装类型总是一个好主意 Integer
用一个java.util.Map.有几种实现:
HashMap:O(1)查找,不维护键的顺序TreeMap:O(log n)查找,维护键的顺序,因此您可以按保证顺序迭代它们LinkedHashMap:O(1)查找,按照它们添加到地图的顺序迭代键.你使用它们像:
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("Stop me", 11);
map.put("Feed me", 12);
int value = map.get("Stop me");
Run Code Online (Sandbox Code Playgroud)
为了更方便地使用集合,请查看Google Collections库.这很棒.
你Map在Java中使用.
请注意,您不能使用int(或任何其他基本类型)作为泛型类型参数,但由于自动装箱,它的行为几乎就像是一个Map<String, int>而不是一个Map<String, Integer>.(但是,您不希望在性能敏感的代码中进行大量的自动装箱.)
Map<String, Integer> entries = new HashMap<String, Integer>();
entries.put("Stop me", 11);
entries.put("Feed me", 12);
entries.put("Walk me", 13);
int value = entries.get("Stop me"); // if you know it exists
// If you're not sure whether the map contains a value, it's better to do:
Integer boxedValue = entries.get("Punch me");
if (boxedValue != null) {
int unboxedValue = boxedValue;
...
}
Run Code Online (Sandbox Code Playgroud)