开发者

Hashmap within a Hashmap

开发者 https://www.devze.com 2023-03-17 18:32 出处:网络
I have a hash开发者_如何学Gomap Map<String, Object> grpFields = new HashMap<String, Object>();

I have a hash开发者_如何学Gomap

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?


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?


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


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


Instead of :

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

Try

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号