Java 使用计数器将数组插入哈希映射
所以我在理解这段代码时遇到了一些困难。for each输入数组中的字符串以及计数相同字符串数的计数器,但计数器是如何做到这一点的 传递给计数器的数字是多少:Java 使用计数器将数组插入哈希映射,java,arrays,count,insert,hashmap,Java,Arrays,Count,Insert,Hashmap,所以我在理解这段代码时遇到了一些困难。for each输入数组中的字符串以及计数相同字符串数的计数器,但计数器是如何做到这一点的 传递给计数器的数字是多少:Integer count=map.get(nextString) if语句做什么呢 HashMap<String, Integer> map = new HashMap<>(); for (String nextString : inArray) { Integer cou
Integer count=map.get(nextString)代码>
if语句做什么呢
HashMap<String, Integer> map = new HashMap<>();
for (String nextString : inArray) {
Integer count = map.get(nextString);
if (count == null) {
count = 1;
} else {
count = count + 1;
}
map.put(nextString, count);
}
HashMap map=newhashmap();
for(字符串下一个字符串:inArray){
整数计数=map.get(nextString);
如果(计数=null){
计数=1;
}否则{
计数=计数+1;
}
map.put(下一个字符串,计数);
}
这里我们寻找与键相关的值(在本例中是数组中的字符串)
因为我们正在用给定字符串出现的次数更新映射,如果没有与键关联的值,则该字符串尚未计数,因此我们将count
设置为1,因为它是该字符串在数组中的第一次出现
if (count == null) {
count = 1;
} else {
count = count + 1;
如果上面的If语句没有执行,这意味着有一些值与字符串关联,所以我们可以增加它,然后将它放回映射中
}
map.put(nextString, count);
}
问题到底是什么?您知道java HashMap是如何工作的吗?请修复懒惰标识,而不是复制OP使用的混乱样式。
} else {
count = count + 1;
}
map.put(nextString, count);
}