Java:使用通配符(*)表示HashMap的密钥

时间:2015-10-13 00:42:04

标签: java hashmap

我要做的是创建一个看起来像这样的HashMap。

enter image description here

我认为通配符*可以用作键,所以如果abc以外的任何字符(让我们说{{1}搜索到,这个HashMap将返回x

10

但是,当我在此地图中搜索密钥 for (int j = 0; j <= 2; j++) { table.put(pattern[j], (pattern.length - 1 - j)); //This part is actually not the same as the original code. //The keys are a,b,c, and the values are 1,2,3 respectively } table.put('*', 10); 时,会返回x,因此很明显null不能直接用作通配符密钥。我跟着this page,但显然这对HashMap不起作用。

如果你能提供任何见解来解决这个问题,我将不胜感激。

2 个答案:

答案 0 :(得分:3)

Java 1.8支持getOrDefault

所以你可以使用map.getOrDefault(key,defaultValue)

答案 1 :(得分:0)

最好单独处理它,而不是创建一个新的Map类。 你可以用一些包装类做这样的事情:

public Object getWithDefault(key){
    if (hashMap.get(key) == null){
        return hashMap.get("*");
    }
}

然后用包装类

调用它
wrapper.getWithDefault('d');  // returns 10.