HashMap containsKey为Integer返回false

dda*_*lis -2 java integer hashmap containskey

我有这个简单的代码,我发现对于最后一个数组,containsKey方法返回总是false.

int[] indices = new int[] { 1, 3, 5, 7, 9 };

Map<Integer, Integer> seen = new HashMap<>();

for (int i = 0; i < indices.length - 1; i++) {
    seen.put(indices[i], i);
}
Run Code Online (Sandbox Code Playgroud)

除了以下所有其他都是

System.out.println("!!!!! " + seen.containsKey(9) );
Run Code Online (Sandbox Code Playgroud)

还有新的

int[] { 1, 3, 5, 7 };
Run Code Online (Sandbox Code Playgroud)

除了以下所有其他都是

System.out.println("!!!!! " + seen.containsKey(7) );
Run Code Online (Sandbox Code Playgroud)

这背后的逻辑是什么?

小智 6

在for循环中

for (int i = 0; i < indices.length - 1; i++) 
Run Code Online (Sandbox Code Playgroud)

将条件更改为i <= indices.length - 1 或使用其他选项i < indices.length

在您的代码中,您只将数组的最后一个元素添加到地图中.


Era*_*ran 5

你没有把你的indices数组的最后一个元素放在你的Map.

更改

for (int i = 0; i < indices.length - 1; i++) {
    seen.put(indices[i], i);
}
Run Code Online (Sandbox Code Playgroud)

for (int i = 0; i < indices.length; i++) {
    seen.put(indices[i], i);
}
Run Code Online (Sandbox Code Playgroud)