padawan
padawan

Reputation: 1315

How to Initialize Map<Integer, Map<Integer, Float>>?

I want to operate on a Map<Integer, Map<Integer,Float>>. This is how I initialize:

Map<Integer, Map<Integer,Float>> map = new TreeMap<>();
for(int i=0; i<100; i++)
    map.put(i, new TreeMap<>());

but I always get null for entrySet. When I try to add an element

map.get(i).put(j.getKey(), d);

where i and j are Map.Entry<Integer, Point3f>, it does nothing. (Point3f is an object from the library vecmath)

Edit: I changed it to HashMap but now I get NullPointerException.

Upvotes: 0

Views: 577

Answers (2)

awksp
awksp

Reputation: 11867

To be honest, I'm not sure why entrySet() seems to be returning null for you, but the map initialization appears to be working for me, and looks pretty OK to me.

The problem is in map.get(i).put(j.getKey(), d);, for the types of i and j you stated. You declared map to be Map<Integer, Map<Integer, Float>>, which means map has Integer keys and Map<Integer, Float> values. Thus, when you call get(i) with the key i being Map.Entry<Integer, Point3f>, map can't find an entry corresponding to that particular key, so it returns null. Then you get a NullPointerException when you try to call put on the map you thought you got.

Upvotes: 1

Shriram
Shriram

Reputation: 4411

Map<Integer, Map<Integer,Float>> map = new TreeMap<Integer, Map<Integer,Float>>();

Map<Integer,Float> f =  map.get(5);
f.put(4,5.6f);

Upvotes: 0

Related Questions