【发布时间】:2020-10-23 22:55:32
【问题描述】:
我正在使用 HashMap
HashMap<String, Integer> count = new HashMap<>();
// List<String≥ words = ...;
for (String word : words) {
if (!count.containsKey(word)) {
count.put(word, 0);
}
count.put(word, count.get(word) + 1);
}
是否有可能,对于同一个单词,计数增加超过 1 是因为我同时在同一个键上执行 put 和 get?即让我们说这个词=“你好”。最初,count.get(word) => 1。当我执行 count.put(word, count.get(word) + 1) 时,如果我执行 count.get(word),而不是得到 2,我得到 3。
【问题讨论】:
-
count.add(word, 0);甚至不应该编译... -
除了你的问题,上面的代码可以重写成更易读的东西(对于熟悉Java 8中添加的流的人)到
Map<String, Long> count = words.stream().collect(Collectors.groupingBy(Function.identity(),Collectors.counting())); -
我的问题不是关于使用流。我编造了这个场景来专门询问在 HashMap 的同一行中 put() 和 get() 的行为
-
顺便说一句,这不是一个可能的解释,请发布
words的内容 -
这就是为什么我说“除了你的问题”:) 无论如何“我同时在同一个键上执行
put和get? " 在单线程环境中,这些指令不会“同时”被调用,而是按顺序调用,特别是count.put(word, count.get(word) + 1);put方法 arguments 需要被评估(所以count.get(word)+1将生成结果首先)然后可以调用count.put(...);。 “如果我做 count.get(word),而不是得到 2,我得到 3。”不是这个问题的假设(单线程并使用正确的键从正确的地图打印值)。