存储新对象作为hashmap的值?

我试图找到一种方法来存储类的新实例作为Java哈希映射中的值。 这个想法是由Java教师给我的,以便创建一个可用于我正在处理的程序的数据存储结构。

他向我推荐的想法是使用存储计算机名称的hashmap作为键,值将是InfoStor.class类的新实例。 InfoStor包含getName(),setName(),getMemory()等方法……

我有类和方法几乎设置为基本测试,看它是否工作。 我遇到的问题是,一旦我在hashmap中创建了一个新条目,我就无法弄清楚如何使用InfoStor中的方法。

这是我到目前为止的代码;

VMware.class

import java.util.HashMap; public class VMware { public static void main(String[] args) { HashMap  mapper = new HashMap(); mapper.put("NS01", new InfoStor("NS01")); //mapper.get("NS01"). } } 

InfoStor.class

 public class InfoStor { private String vmName; private String platform; private Integer memory; public InfoStor (String name) { vmName = name; } String getName(){ return vmName; } void setPlatform(String p){ platform = p; } String getPlatform(){ return platform; } void setMemory(Integer m){ memory = m; } Integer getMemory(){ return memory; } } 

我想要完成的是这样的(基本想法)。

 Object var = mapper.get("NS01"); System.out.println(var.getMemory()); 

我是以错误的方式来做这件事的吗? 任何帮助表示赞赏谢谢。

问题是您的代码仅指定映射中的值是Object 。 你知道的不止这些,所以告诉编译器这些信息:

 HashMap mapper = new HashMap(); mapper.put("NS01", new InfoStor("NS01")); ... InfoStor value = mapper.get("NS01"); Integer memory = value.getMemory(); 

请注意,为变量类型使用接口通常并不总是更好 – 并且您可以使用菱形运算符进行构造函数调用,让编译器使用类型推断来填充类型参数:

 Map mapper = new HashMap<>(); mapper.put("NS01", new InfoStor("NS01")); ... InfoStor value = mapper.get("NS01"); Integer memory = value.getMemory(); 

如果你声明你的hashmap如下:

 HashMap mapper = new HashMap(); 

然后当你从mapper中获取一个对象时,它将是InfoStor一个实例(你不需要抛出它或担心类转换exception,因为它不是rist类。)

所以:

 InfoStor myStor = mapper.get("somekey"); myStor.getMemory(); // this will work 

否则,如果您坚持使用原始代码中使用的HashMap ,则需要在调用方法之前将其强制转换:

 Object obj = mapper.get("somekey"); ((InfoStor)obj).getMemory(); // cast is required obj.getMemory(); // this will not compile 

您应该阅读Javagenerics。

利用添加到java的generics。 它们有助于编译时类型检查,并且它们使得转换不必要。

  HashMap  mapper = new HashMap(); //you will be able to retrieve an object and then cast it to your InfoStore InforStore isN01 = (InfoStore)mapper.get("N01"); //this will unfortunately be accepted, even thought it's a bug mapper.put("N02", new Integer(0)); ________________________ HashMap  mapper = new HashMap(); //you will be able to retrieve an object and then cast it to your InfoStore InforStore isN01 = mapper.get("N01"); //no cast 

你走在正确的轨道上……

将地图初始化为:

 HashMap  mapper = new HashMap(); 

然后在向地图添加对象后检索它们:

 InfoStor var = mapper.get("NS01"); System.out.println(var.getMemory()); 

你可以通过使用数组来烹饪…例如,如果你可以在数组中存储对象然后使用这个想法在哈希映射中实现它…我不知道你如何设计但我曾经卡在那里并通过像这样

例…

class级公主{

 int age; public princess(int age){ this.age=age; } public int getAge(){ return this.age; } 

}

public class hashmaptest {

 public static void main(String[] args) { princess[] p=new princess[10]; HashMap scores = new HashMap(); scores.put("a",new princess(6)); scores.put("b",new princess(7)); p[0]=(princess)scores.get("a"); System.out.println(p[0].getAge()); p[0]=null; p[0]=(princess)scores.get("b"); System.out.println(p[0].getAge()); } 

}