我正在尝试找到一种方法来将类的新实例存储为 Java HashMap 中的值。这个想法是一位 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 <String, Object> 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<String, InfoStor> mapper = new HashMap<String, InfoStor>();
mapper.put("NS01", new InfoStor("NS01"));
...
InfoStor value = mapper.get("NS01");
Integer memory = value.getMemory();
请注意,通常对变量类型使用接口(interface)虽然并不总是更好 - 您可以使用菱形运算符进行构造函数调用,让编译器使用类型推断来填充类型参数:
Map<String, InfoStor> mapper = new HashMap<>();
mapper.put("NS01", new InfoStor("NS01"));
...
InfoStor value = mapper.get("NS01");
Integer memory = value.getMemory();
关于java - 将新对象存储为 HashMap 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12099843/