【问题标题】:HashMap of ArrayList causing nullpointerexceptionArrayList的HashMap导致nullpointerexception
【发布时间】:2013-02-12 19:09:55
【问题描述】:

我有一个 ArrayLists 的 HashMap 作为值,但是当我添加 ArrayLists 时 HashMap 保持为空,然后当我尝试 get() ArrayList 时抛出 NullPointerException。很混乱。

Random rand = new Random();
HashMap<String,ArrayList<Integer>> hands = new HashMap<String,ArrayList<Integer>>();
HashMap<Integer, Boolean> deck = new HashMap<Integer, Boolean>();

for(int x=0;x<4;x++){
    for(int y=0;y<4;y++){
    hands.put(x+SUITS[x], new ArrayList<Integer>());
    }
}       
    for(int x=0;x<4;x++){
        for(int y=0;y<13;y++){
            int randCard = rand.nextInt(52)+1;
            if(!deck.containsKey(randCard)){
                deck.put(randCard, true);

                hands.get(x+cardSuit(randCard)).add(randCard);

            }else y--;
        }
    }

【问题讨论】:

  • 如果无法查看 cardSuit() 方法,很难进行故障排除,但很明显,当您获取时,没有映射到您正在使用的键的值。
  • 查看您的代码,没有理由期望您尝试取消引用的任何键都会出现。 put 时使用的键与 get 时使用的键完全不同。

标签: java arraylist nullpointerexception hashmap


【解决方案1】:

您正在使用如下所示的键将值放入映射中:

someInt + ""

您正在使用如下所示的键从映射中获取值:

someInt + cardSuit(randCard)

除非 cardSuit 总是返回一个空字符串,否则它们将是不同的键。

【讨论】:

  • 对不起,我在调试时更改了它,但这不是问题。 HashMap 在代码执行期间永远不会增加大小,并且保持 size=0。很抱歉没有澄清
  • @WarrenGreen - 这绝对不可能。您的代码必须至少将值放在名为 Hands 的地图中。您的 for 循环肯定会执行,并且(除非它在第一次迭代时抛出异常)它会在每次迭代时在映射中放置一个值。
  • @WarrenGreen - 您应该添加调试语句(最好使用调试器)以查看您的代码在做什么。每次你把东西放进地图时,打印出键和值。在调用Map.get 之前,您应该打印密钥并通过调用Map.containsKey 检查元素是否存在。
【解决方案2】:

这里 cardSuit(randCard) 正在返回地图中没有的东西。

您将x+"" 作为键。

但是当你检索时,你正在使用这个:

x+"something"

【讨论】:

  • 请尝试将代码格式用于类似代码的内容,而不是大部分不是代码的完整答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-08-06
  • 2016-03-07
  • 2017-05-16
  • 1970-01-01
  • 2014-06-09
  • 2015-11-07
  • 1970-01-01
相关资源
最近更新 更多