简体   繁体   English

在Java中使用HashMaps

[英]Using HashMaps in Java

Basically I'm making this Java program in BlueJ, in which the player is in the world of The Lord of the Rings. 基本上,我是在BlueJ中制作此Java程序的,其中播放器位于《指环王》的世界中。 I created separate packages for weapons, items etc. I have a class Main outside all the packages(in the main body of the project screen). 我为武器,物品等创建了单独的程序包。在所有程序包的外部(在项目屏幕的主体中)有一个Main类。 In there, I tried something. 在那儿,我尝试了一些东西。

public static void test()throws Exception{
        System.out.println("There is a brass sword and an iron sword. Which do you want?");
        Scanner in = new Scanner(System.in);
        String s = in.next();
        HashMap options = new HashMap();
        options.put("brass", new Sword());
        options.put("iron", new Sword());
        Sword k = options.get(s);
}

I want the above method to return a Sword object to me. 我希望以上方法可以将Sword对象返回给我。 This does not work, unfortunately. 不幸的是,这不起作用。 Any help....? 任何帮助....?

Just use the parametrized type HashMap , declare the HashMap as 只需使用参数化的HashMap类型,将HashMap声明为

HashMap<String, Sword> options = new HashMap<String, Sword>();

I want the above method to return a Sword object to me. 我希望以上方法可以将Sword对象返回给我。

Then change the method return type and add a return to it: 然后更改方法的返回类型并为其添加返回值:

public static Sword test()throws Exception{
        System.out.println("There is a brass sword and an iron sword. Which do you want?");
        Scanner in = new Scanner(System.in);
        String s = in.next();
        HashMap<String, Sword> options = new HashMap<String, Sword>();
        options.put("brass", new Sword());
        options.put("iron", new Sword());
        Sword k = options.get(s);
        return k;
}

Use following code: 使用以下代码:

public static Sword test()throws Exception{
    System.out.println("There is a brass sword and an iron sword. Which do you want?");
    Scanner in = new Scanner(System.in);
    String s = in.next();
    HashMap<String, Sword> options = new HashMap<String, Sword>();
    options.put("brass", new Sword());
    options.put("iron", new Sword());
    return options.get(s);
}

如果您希望您的方法返回Sword对象,则应将public static void test()更改为public static Sword test()并在方法结束时调用return sword

The default hashMap accepts two generic types HashMap<Object,Object> which represents HashMap<Key,Value> with your code you will have to cast the options.get(s) to Sword but with that you don't use the power of Generics so recommend the @BackSlash's answer since you won't need casting. 默认的hashMap接受两种通用类型HashMap<Object,Object> ,它们代表HashMap<Key,Value>并且您的代码必须将options.get(s)Sword但是您不使用Generics的功能因此,建议使用@BackSlash的答案,因为您不需要强制转换。

More on Generics: http://www.tutorialspoint.com/java/java_generics.htm 有关泛型的更多信息: http : //www.tutorialspoint.com/java/java_generics.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM