如何从Java的HashMap中获取对象 [英] How to get an object from a HashMap in Java

查看:857
本文介绍了如何从Java的HashMap中获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从给定密钥的HashMap中获取Test对象的速度,但我不太确定如何去做。我试过这种方式,但它的错误:

  hash.values()。getSpeed(); 

有什么帮助吗?谢谢

  class Test {

private String id;
私人字符串名称;
private int speed;

public Test(String id,String name,int speed){
this.id = id;
this.name = name;
this.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>();

测试c1;
测试c2;

c1 = new Test(Z,B,4);
c2 = new Test(Y,D,7);
hash.put(A,c1);
hash.put(C,c2);


$ / code $ / pre

解决方案

 测试c1; 
测试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);


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. 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");

这篇关于如何从Java的HashMap中获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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