[英]How to get an object from a HashMap in Java
I'm trying to get the speed of a Test object from a HashMap when given the key but I'm not quite sure how to do it. 在给出密钥时,我试图从HashMap获取Test对象的速度,但我不太清楚如何做到这一点。 I tried this way but its wrong: 我试过这种方式,但错了:
hash.values().getSpeed();
Any help? 有帮助吗? Thanks 谢谢
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");
Map接口中有一个方法,我认为有以下签名+返回类型:
E get(T key);
hash.get("A")
,或者更一般地说: hash.get(key)
,其中key
是hash.put(key, value)
调用的第一个参数。
get
is the inverse of put
. get
是put
的倒数。 So just hash.get("C");
所以只是hash.get("C");
will give you c1
, etc. 会给你c1
等
I suggest you look over Javadoc of the classes you use more thoroughly before posting. 我建议你在发布之前仔细查看你使用的类的Javadoc。
public class Driver {
public static void main(String[] args) {
HashMap<String, Test> hash = new HashMap<String, Test>();
Test c1;
Test c2;
c1 = new Test("A", "Maruthi", 4);
c2 = new Test("B", "Toyota", 7);
hash.put("A", c1);
hash.put("B", c2);
for(Test t:hash.values()) {
System.out.println(t.getSpeed() + " " + t.getId() + " " + t.getName());
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.