我正在尝试在给定 key 时从 HashMap 获取测试对象的速度,但我不太确定该怎么做。我试过这种方式,但它是错误的:
hash.values().getSpeed();
有什么帮助吗?谢谢
class Test {
private String id;
private String name;
private int speed;
public Test(String id, String name, int speed) {
this.id = id;
this.name = name;
this.speed = speed;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getSpeed() {
return speed;
}
}
public class Driver {
public static void main(String[] args) {
HashMap<String, Test> hash = new HashMap<String, Test>();
Test c1;
Test c2;
c1 = new Test("Z", "B", 4);
c2 = new Test("Y", "D", 7);
hash.put("A", c1);
hash.put("C", c2);
}
}
最佳答案
Test c1;
Test c2;
c1 = new Test("Z", "B", 4);
c2 = new Test("Y", "D", 7);
hash.put("A", c1);
hash.put("C", c2);
Test getC1 = (Test)hash.get("A");
Test getC2 = (Test)hash.get("C");
关于java - Java 如何从 HashMap 中获取对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7857935/