【发布时间】: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