我遇到了 this post对于不区分大小写的 HashMap 并尝试实现它,但我没有得到预期的结果。出于某种原因,当我使用不同的外壳并返回 null 时,它没有返回值,我认为在这种情况下你并不真的需要一个非默认构造函数,但我不确定。
public class CaseInsensitiveMap extends HashMap<String, Integer> {
@Override
public Integer put(String key, Integer value) {
return super.put(key.toLowerCase(), value);
}
// not @Override because that would require the key parameter to be of type Object
public Integer get(String key) {
return super.get(key.toLowerCase());
}
}
这样使用;
HashMap<String, Integer> stuff = new CaseInsensitiveMap();
stuff.put("happy", 11);
System.out.println(stuff);
Integer result = stuff.get("HAPPy");
System.out.println(result);
System.out.println(stuff);
但结果是;
{happy=11}
null
{happy=11}
最佳答案
简单修复;
CaseInsensitiveMap stuff = new CaseInsensitiveMap();
打印出来;
{happy=11}
11
{happy=11}
CaseInsensitiveMap
正在扩展 HashMap<String, Integer>
所以它是它的一个子类,事实上你引用了 stuff
作为HashMap
(作为父类(super class))允许它使用默认 get
方法。您甚至可以在 IDE 中看到您的自定义 get(String)
在 CaseInsensitiveMap
甚至没有使用。
如果您对子类使用父类(super class)引用,则只会使用重写的方法,就像您在代码中所做的那样。这就是为什么只有您的自定义 put(String, Integer)
方法有效,因为它覆盖了 super
中的方法.
Referencing Subclass objects with Subclass vs Superclass reference有关该问题的更多信息。
关于java - java中字符串的不区分大小写的 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53272732/