当我尝试查找刚刚放入hashmap的值时,为什么会出现Runtime异常?

Jim*_*Jim 2 java string hashmap

有人可以向我解释为什么以下代码段会抛出运行时异常吗?

int i = 0;
for ( ; i < TOTAL; i++ ) {
    String value = "" + i;
    int key = numbers[i];                
    map.put(key, value);
}

i = 0;
for ( ; i < TOTAL; i++ ) {
    String value = "" + i;
    int key = numbers[i];
    String valueInMap = map.get(key);
    if(valueInMap == null || !valueInMap.equals(value)) {
        throw new RuntimeException("Impossible!");
    }
}
Run Code Online (Sandbox Code Playgroud)

这是整个程序,除了我numbers[]用随机数填充的部分.

我指的是throw new RuntimeException("Impossible!");我得到这个例外

das*_*ght 6

我填写numbers[]随机数字.

您会收到异常,因为并非所有TOTAL项目中的值numbers[]都是唯一的.发生这种情况时,新值会覆盖旧值,因此在第二个循环中会得到错误的结果.

为了确保永远不会发生这种情况,请将TOTAL随机值放入a中,HashSet<Integer>然后再将它们复制到numbers[]数组中.