返回Hash Map对象的多个值

时间:2017-10-26 04:48:22

标签: java object hashmap

嘿那里有很棒的人!在这已经太久了,找不到答案。我需要显示状态(键)和Capital对象; name,pop和square Mi(值:string,int,int)。我该如何显示这些?当我正常运行时运行null(键,值)我尝试.get并且有一个静态错误。请帮忙!?

// Other class get set

public class Capital  {

    public String name;
    public int pop;
    public int sqM;

    public Capital(String nameIn, int popIn, int sqMIn){
        this.name = nameIn;
        this.pop = popIn;
        this.sqM = sqMIn;
    }
    public String getName(){
        return name;
    }
    public void setName(String name){
        this.name = name;
    }
    public int getPop(){
        return pop;
    }
    public void setPop(int pop){
        this.pop = pop;
    }
    public int getSquare(){
        return sqM;
    }
    public void setSquare(int sqM){
        this.sqM = sqM;
    }
}
public class App {
    
    public static void main(String[] args){
        
        HashMap<String, Capital> StateCap = new HashMap<>();
        
        Capital capitalOne = new Capital("Montgomery", 258, 768);
        StateCap.put("Alabama", (capitalOne));
        Capital capitalTwo = new Capital("Juneau", 576, 94);
        StateCap.put("Alaska", (capitalTwo));
        
        Set<String> keys = StateCap.keySet();
        
         for (String state : keys) {
            //This is where I need help I believe.

1 个答案:

答案 0 :(得分:0)

嗯,你差不多了。您只需要了解HashMap的功能。 你走了:

    for (String state : keys) {
       // Get the value i.e. `Capital` object corresponding to the `key` i.e. `State`
        Capital cap = StateCap.get(state);
        System.out.println(cap.getName());
        System.out.println(cap.getPop());
        .
        .
        blah blah
    }

另请阅读entrySet()方法。

N.B。: :遵循变量的命名约定(例如:StateCapstateCap)。