1
 public class arraylst
 {
   static HashMap<String,List<String>>hm;
   public static void main(String[] args)
   {
       hm.put("2",Arrays.asList("a","b","c"));
   }
 } 

I don't understand why this causes NullPointerException.

Can someone please help me out?

1
  • 7
    Because hm is null -- you never assign an object to it. Now, let's please close this question. Commented Dec 27, 2011 at 4:08

5 Answers 5

4

You need to set hm:

hm = new HashMap<String, List<String>>();

before you use it.

Sign up to request clarification or add additional context in comments.

Comments

2

You need to put a HashMap<String,List<String>> into your (initially empty) hm field.

Comments

2

Use

static HashMap<String, List<String>> hm = new HashMap<String, List<String>>();

Comments

1

Unlike primitive variables, the Classes should be explicitly initialized. So create an instance of HasMap.

Comments

0

You are pointing to a reference which don't have a Object. So you are trying to refer a Object which haven't yet created.

So using the "new" key word create an Object to overcome the exception

static HashMap<String,List<String>> hm = new HashMap<String,List<String>>();

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.