【问题标题】:How to use a HashMap returned from a method如何使用从方法返回的 HashMap
【发布时间】:2021-07-09 00:52:51
【问题描述】:

这里我有一个在方法中创建 HashMap 的程序

import java.util.HashMap;


class Evan {
  public HashMap<String,Double> abilities_get() {
     HashMap<String,Double> abilities = new HashMap<String,Double>();
     abilities.put("stealth", 1.5);
     abilities.put("strength", 1.2);
     abilities.put("accuracy", 1.0);
     abilities.put("intelligence", 2.0);
     return abilities;
     
 }
 }

 public class Main {
 
    public static void main(String[] args) {
       Evan evan = new Evan();
       evan.abilities_get();
       abilities.get("stealth");
}
}

由于在 main 方法中找不到“能力”,因此该程序无法运行。我怎样才能做到这一点,以便我可以在主函数中使用我的 HashMap。

【问题讨论】:

    标签: java class hashmap return return-value


    【解决方案1】:
    class Evan {
        public HashMap<String,Double> abilities_get() {
            HashMap<String,Double> abilities = new HashMap<String,Double>();
            abilities.put("stealth", 1.5);
            abilities.put("strength", 1.2);
            abilities.put("accuracy", 1.0);
            abilities.put("intelligence", 2.0);
            return abilities;
    
        }
    }
    
    class Main {
    
        public static void main(String[] args) {
            Evan evan = new Evan();
            evan.abilities_get();
            Double stealth = evan.abilities_get().get("stealth");
            System.out.println(stealth);
        }
    }
    

    试试看

    【讨论】:

    • 非常感谢你!我一直在寻找这个,但显然它只是一个快速添加(我会在几分钟内接受这个作为答案,因为有一个计时器可以让我接受答案的速度)。
    • 一开始很难。我建议你从 github 查看现成的示例。最重要的是不要放弃!代码上需要 cmets 吗?
    • 我很好,我相信我明白了,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多