【问题标题】:Why do I get a Runtime exception when I try to find values I just put in the hashmap?当我尝试查找刚刚放入哈希图中的值时,为什么会出现运行时异常?
【发布时间】:2015-09-14 12:37:56
【问题描述】:

有人可以向我解释一下为什么下面的 sn-p 会抛出运行时异常吗?

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!");
    }
}

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

我指的是throw new RuntimeException("Impossible!");我得到了这个异常

【问题讨论】:

  • @Pshemo:我的条件检查中的文本Impossible
  • 您是否尝试过调试?比如找回后打印valueInMap
  • @kdgregory:是的,它打印 0

标签: java string hashmap


【解决方案1】:

我用随机数填充numbers[]

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

为确保这种情况永远不会发生,请将 TOTAL 随机值放入 HashSet&lt;Integer&gt;,然后再将它们复制到 numbers[] 数组中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 2013-01-03
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多