java - java中字符串的不区分大小写的 HashMap

标签 java case superclass

我遇到了 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/

相关文章:

java - JPanel 的尺寸比 Scrollpane 的尺寸大

java - 如何实现Android ActionBar 后退按钮?

java - 在二维数组中生成随机数

mysql - sql server 中 where 子句中的 case 语句与 else 始终为真

mysql - SQL 查询 - CASE 意外标记

java - hibernate 一对一还是组件?

eclipse - Eclipse 中不修改大小写进行替换

c++从派生类指针获取基类对象?

Java 多态性与 ArrayList

java - 3 个支票账户 2 个 build 者为客户提供没有 overdraw 的服务,但是不想 overdraw 的客户可以得到一个