gpt4 book ai didi

java - 返回 Hash Map 对象多个值

转载 作者:太空宇宙 更新时间:2023-11-04 11:00:33 24 4
gpt4 key购买 nike

嘿,这里有很棒的人!关注这个问题太久了,找不到答案。我需要显示状态(键)和资本对象; 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.

最佳答案

好吧,你已经很接近了。您只需多了解一点 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() 方法。

注意::遵循变量的命名约定(例如:StateCapstateCap)。

关于java - 返回 Hash Map 对象多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46946041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com