1

Im using HashMap in my application and sometimes I need to add a key (String) with a null value (emty array list of objects). But Netbeans 7.4 says:

Exception in thread "main" java.lang.NullPointerException
    at test.Version.main(Version.java:35)
Java Result: 1

to this code:

        HashMap<String, ArrayList<Object[]>> d = null;

        ArrayList<Object[]> a;
        a = new ArrayList<>();

        d.put("key1", a);

I dont want to use a MultiMap. Is there any other way how to solve it easily?

3
  • 2
    You haven't initialized d to an instance of HashMap. You're trying to call put on a null reference. Commented Oct 18, 2013 at 13:21
  • 2
    d is null! Please add row d = new Hashmap<String, ArrayList<Object[]>> Commented Oct 18, 2013 at 13:22
  • 2
    Just initialize d, for example d = new HasMap<String, ArrayList<Object>>(); Commented Oct 18, 2013 at 13:24

4 Answers 4

5

You're getting a NullPointerException because d is null, and you try to de-reference it with your call to d.put("key1", a).

You can fix this by changing your initialization of d to

HashMap<String, ArrayList<Object[]>> d = new HashMap<String, ArrayList<Object[]>>();

Now that d isn't null, you can use the methods native to HashMap, like d.put("key1", a).

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

Comments

4
Map<String, List<Object[]>> d = new HashMap<String, List<Object[]>>;
List<Object[]> a = new ArrayList<Object[]>();
d.put("key1", a);

If d is null, then -> NullPointerException ;)

Comments

2

You can't call map.put without creating an instance of it at first, your map is still null.

You need to instantiate it first:

Map<String, ArrayList<Object[]>> d = new HashMap<String, ArrayList<Object[]>>();

and then:

d.put("key1", a);

Comments

2

You wrote:

HashMap<String, ArrayList<Object[]>> d = null;

and then you try to put element to a null:

d.put("key1", a);

You must first declare instance of HashMap:

 HashMap<String, ArrayList<Object[]>> d = new HashMap<String, ArrayList<Object[]>>();

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.