Will
Will

Reputation: 8631

Hashmap within a Hashmap

I have a hashmap

Map<String, Object> grpFields = new HashMap<String, Object>();

which is contained within another hashmap:

Map<Integer, Object> targetFields = new LinkedHashMap<Integer, Object>();

I can see it within debug mode:

20005=0, 453={452-2=7, 452-0=1, 452-1=17, 448-2=81, 448-1=0A, 447-2=D, 447-1=D, 447-0=D, 448-0=0A}, 11=1116744Pq2Q,

where 453 is the Hashmap, however when trying to extract the hashmap from the parent hashmap using:

HashMap <String, Object> grpMap453 = (HashMap)targetFields.get(453);

I'm thrown:

java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String

Surely the call targetFields.get(453); should simply return a hashmap?

Upvotes: 6

Views: 5312

Answers (4)

Rajendra Jajra
Rajendra Jajra

Reputation: 1

To put value in HashMap

HashMap<String, Map<?,?>> hashMap = new HashMap<String, Map<?,?>>();

Map<String, String> internalHashMap  = new HashMap<String, String>()

internalHashMap.put("TEST_KEY1","TEST_Value1");
internalHashMap.put("TEST_KEY2","TEST_Value2");
internalHashMap.put("TEST_KEY3","TEST_Value3");

hashMap.put("TEST_KEY",internalHashMap);

Upvotes: 0

TomWolk
TomWolk

Reputation: 987

As already noted you cannot get that error from the line of code where you extract the HashMap. However you will receive that error with following line of code:

String s11 = (String)targetFields.get(453);

Upvotes: 0

user756212
user756212

Reputation: 522

Instead of :

HashMap <String, Object> grpMap453 = (HashMap)targetFields.get(453);

Try

HashMap <String, Object> grpMap453 = (HashMap<String,Object>)targetFields.get(453);

Upvotes: -1

Harry Joy
Harry Joy

Reputation: 59660

I've tried making a demo on the basis of what you have described and found no error in it.

    HashMap<String, Object> hashMap = new HashMap<String, Object>();
    hashMap.put("123", "xyz");
    HashMap<Integer, Object> map = new HashMap<Integer, Object>();
    map.put(453, hashMap);
    HashMap<String, Object> newMap = (HashMap<String, Object>) map.get(453);

    System.out.println("Main map "+ hashMap);
    System.out.println("Map inside map "+map);
    System.out.println("Extracted map "+newMap);

It gives warning at line HashMap<String, Object> newMap = (HashMap<String, Object>) map.get(453); that is "Type safety: Unchecked cast from Object to HashMap" but no error at all.

Are you doing the same?

Upvotes: 11

Related Questions