0

I have a HashMap of ArrayLists for values but the HashMap remains empty when I add the ArrayLists and then throws an NullPointerException when I try to get() the ArrayList. VERY confused.

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--;
        }
    }
2
  • Pretty hard to troubleshoot without being able to see the cardSuit() method, but it's obvious that there is no value mapped to the key you're using when you get.
    – jahroy
    Feb 27, 2013 at 4:35
  • Looking at your code there is no reason to expect that any of the keys you try to dereference will be present. They keys you use when you put are completely different than the keys you use when you get.
    – jahroy
    Feb 27, 2013 at 4:37

2 Answers 2

5

You're putting values into the map with keys that look like this:

someInt + ""

You're getting values from the map with keys that look like this:

someInt + cardSuit(randCard)

Unless cardSuit always returns an empty string, those are going to be different keys.

3
  • Sorry, I changed it while debugging but that is not the problem. The HashMap never increases in size during the execution of code and remains at size=0. Sorry for not clarifying Feb 28, 2013 at 6:22
  • @WarrenGreen - That's absolutely impossible. Your code must put values in at least the map named Hands. Your for loop is sure to execute and (unless it's throwing an Exception on the first iteration) it will put a value in the map on every iteration.
    – jahroy
    Feb 28, 2013 at 6:27
  • @WarrenGreen - You should add debug statements (better yet use a debugger) to see what your code is doing. Each time you put something into a map, print out the key and the value. Before you call Map.get, you should print the key and check to see if the element exists by calling Map.containsKey.
    – jahroy
    Feb 28, 2013 at 6:34
3

Here cardSuit(randCard) is returning something that is not in the map.

You are putting x+"" as the keys.

But when you are retrieving you are using this:

x+"something"

1
  • Please try to use code formatting for code-like things, not entire answers that are mostly not code. Feb 27, 2013 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.