C# 难民寻求 Java 集合的一些帮助
-
06-07-2019 - |
题
我需要将键/值信息存储在某种类型的集合中。在 C# 中,我定义一个这样的字典:
var entries = new Dictionary<string, int>();
entries.Add("Stop me", 11);
entries.Add("Feed me", 12);
entries.Add("Walk me", 13);
然后我将访问这些值:
int value = entries["Stop me"];
我如何在 Java 中执行此操作?我见过的例子 ArrayList
, ,但如果可能的话,我想要使用泛型的解决方案。
解决方案
你想使用一个 Map
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("Stop me", 11);
Integer i = m.get("Stop me"); // i == 11
请注意,在最后一行,我可以说:
int i = m.get("Stop me");
这是(使用 Java 的自动拆箱)的简写:
int i = m.get("Stop me").intValue()
如果给定键处的映射中没有值,则 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");
为了更加方便地使用集合,请查看 Google 收藏库. 。太棒了。
你用一个 Map
在爪哇。
请注意,您不能使用 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;
...
}
看起来你正在寻找类似的东西 HashMap
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Stop Me", 11);
map.put("Feed Me", 12);
map.put("Walk Me", 13);
Integer x; // little hack
int value = (x = a.get("aaa")) == null? 0 : x;
作为替代方案,您可以尝试枚举:
enum Action {
STOP(11),
FEED(12),
WALK(13);
private final int value;
private Action(int value) {
this.value = value;
}
public int value() {
return value;
}
public static Action valueOf(int value) {
for (Action action : values()) {
if (action.value == value) {
return action;
}
}
return null; // or a null-object
}
}
测试:
public void action() {
Action action = Action.valueOf("FEED");
// or Action.FEED for more compile-time safety
int value = action.value();
// instantiating by code
Action walk = Action.valueOf(13);
}
你肯定想要一个 HashMap
, ,这是 C# 的 Java 版本 Dictionary
.
不隶属于 StackOverflow