在Java中创建复杂的HashMap [英] Creating complex HashMap in Java

查看:163
本文介绍了在Java中创建复杂的HashMap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建HashMap的最简单的方式是这样的:

What is the easiest way to create a HashMap like this :

( student1 => Map( name => Tim,         
                   Scores => Map( math => 10,
                                  physics => 20,
                                  Computers => 30),
                   place => Miami,
                   ranking => Array(2,8,1,13),
                ), 
student2 => Map ( 
                  ...............
                  ...............
                ),
............................
............................
);

我尝试过:

HashMap record = new HashMap();
record.put("student1", new HashMap());
record.get("student1").put("name","Tim");
record.get("student1").put("Scores", new HashMap());

但是我收到错误。我这样做是因为, record.get(student1)是一个HashMap对象,所以我假设一个 put

But I get error. I do it that way because, record.get("student1") is a HashMap object, so I assume a put on that should work, and so on.

如果它不起作用,最好的方法是什么?

If it doesnt work, what is the best way to do it ?

推荐答案

你得到这个异常,因为 get()返回一个类型 Object 。您需要将其转换为地图

You get that exception because get() returns a type Object. you need to cast that to a Map.

((Map)record.get("student1")).put("name","Tim");

这篇关于在Java中创建复杂的HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆