简体   繁体   中英

Java HashMap<String, ArrayList<Object[]>> how to add an empty array?

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?

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) .

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 ;)

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);

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[]>>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM