user9467051
user9467051

Reputation: 128

Initialize a HashMap<Integer, List<Object>>

I'm trying to fill the values of the hashmap

HashMap<Integer,List<Human>> hm=new HashMap<>(100);

for(int j=0;j<hm.size();j++)
{
    hm.put(j,new ArrayList<>());
}

But when i'm do that :

Human x= new Human();
hm.get(3).add(x);

I get:

java.lang.NullPointerException

Upvotes: 2

Views: 1645

Answers (3)

AxelH
AxelH

Reputation: 14572

You are not getting 100 with hm.size() but 0. You don't get what you have build with that constructor. You have set the "initialCapacitiy" with that constructor :

HashMap(int initialCapacity)

Constructs an empty HashMap with the specified initial capacity and the default load factor (0.75).

But HashMap.size() return the actual number of key-value element.

Returns the number of key-value mappings in this map.

For your information :

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

Instead, simply set 100 in the loop to instanciate your List.

Map<Integer,List<Human>> hm = new HashMap<>();
for(int j=0; j < 100; j++){
    hm.put(j,new ArrayList<>());
}

Or even better, use a constant somewhere like

final static int NB_LIST = 100;

Map<Integer,List<Human>> hm = new HashMap<>();
for(int j=0; j < NB_LIST; j++){
    hm.put(j,new ArrayList<>());
}

Upvotes: 2

Veselin Davidov
Veselin Davidov

Reputation: 7071

hm.size() returns 0 because you still haven't added anything in the hashmap. From java site:

Returns the number of key-value mappings in this map.

You initialize it with some initial size but you have no values inside so your for cycle is not doing anything. If you do it for 1 to 100 instead of 1 to size it will work as you expect.

Upvotes: 1

Maciej
Maciej

Reputation: 1994

hm.size() is zero - because you did not put there anything. 100 parameter is just initialization of the "start capacity" here.

Change your loop to for(int j=0;j<100;j++)

Upvotes: 4

Related Questions