简体   繁体   English

使用带有哈希映射的字符串

[英]Using strings with hashmaps

How would I use a String to specify a specific HashMap .我将如何使用String来指定特定的HashMap

Eg:例如:

public static ConcurrentHashMap<String, Integer> age = new ConcurrentHashMap<String, Integer>(); 
String s = "age";
s.get("Nick");

If you want to Map a person's name to their age, you need如果你想将一个人的名字映射到他们的年龄,你需要

Map<String,Integer> age = new HashMap<>(); // only use ConcurrentHashMap if you intend
                                           // to use that Map from multiple threads
...
age.put("Nick",42);
...
int nicksAge = age.get("Nick");
public class HashMapTest {
    public static HashMap<String, Integer> ageMap = new HashMap<String, Integer>();

    public static void main(String[] args) {
        ageMap.put("Nick", 12);
        Integer age = ageMap.get("Nick");
        System.out.println(age);

    }

}

You can achieve this using Generics您可以使用泛型来实现这一点

https://docs.oracle.com/javase/tutorial/java/generics/ https://docs.oracle.com/javase/tutorial/java/generics/

Generics allows you to specify a type for a map.泛型允许您为地图指定类型。 So instead of using所以而不是使用

public static ConcurrentHashMap age = new ConcurrentHashMap();

You could use你可以用

public static Map<String, Short> age = new ConcurrentHashMap<>();

or any other form of map for example或任何其他形式的地图,例如

public static Map<String, Integer> ageMap = new HashMap<>();

This simplifies the get and put operations.这简化了 get 和 put 操作。

Instead of writing a code such as而不是编写代码,例如

Object o = ageMap.get("Nick");
if(o instanceof Integer) {
    Integer age = (Integer) o;
}

You could simply write你可以简单地写

Integer age = ageMap.get("Nick");

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

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