为什么我的自定义HashMap类扩展了HashMap,没有正确地为put工作?

时间:2016-08-05 23:04:30

标签: java enums hashmap

我正在编写一些代码,其中我有一个扩展HashMap的自定义HashMap类。

自定义HashMap类

public class CaseInsensitiveMap<T> extends HashMap<String, T> {
/**
 * 
 */
private static final long serialVersionUID = 1L;

public T put(String key, T value) {
    return super.put(key.toLowerCase(), value);
 }

 public T get(String key) {
    return super.get(key.toLowerCase());
 }
}

我的枚举将类创建为查找并放置所有值。 put语句无法正常工作,因为它会覆盖值,而值不会填充HashMap表,而是跳过索引。

枚举

public enum UpdateMode{
/**
 * No auto-updates or update notifications will occur. Updates can be performed manually.
 */
UNAVAILABLE("UNAVAILABLE", false),
/**
 * Updates are enabled and the driver will be notified only once per session.
 */
AVAILABLE("AVAILABLE", true),
/**
 * The device will be forced to update with no user notification.
 */
MANDATORY("MANDATORY", true);

private final String code;
private final boolean isAutomatic;

private UpdateMode(String code, boolean isAutomatic)
{
    this.code = code;
    this.isAutomatic = isAutomatic;
}

//private static final CaseInsensitiveMap<UpdateMode> lookup = new CaseInsensitiveMap<UpdateMode>();
private static final HashMap<String, UpdateMode> lookup = new HashMap<String, UpdateMode>();

static {
    for (final UpdateMode t : UpdateMode.values()) {
        lookup.put(t.code(), t);
    }
}

/**
 * Gets the enum from the supplied code string value.
 * @param code
 * @return
 */
public static UpdateMode get(String code) {
    if (lookup.containsKey(StringUtil.nullToEmptyString(code))) {
        return lookup.get(code);
    }

    return AVAILABLE;
}


/**
 * Returns the code value of the UpdateModes ("UNAVAILABLE", "AVAILABLE", "MANDATORY")
 * @return
 */
public String code()
{
    return code;
}


/**
 * Checks if update features are automatic.
 *
 * @return true, if is automatic
 */
public boolean isAutomatic() {
    return isAutomatic;
}

}

这会失败,因为在使用Custom HashMap类时,找不到“UpdateMode”,因为该值已被另一个字符串值替换。

        // Automated updates have been disabled.
    if (!updateServiceContext.getUpdateMode().isAutomatic())
    {
        return;
    }

当我直接使用HashMap时,一切都按预期工作,HashMap表填充了我的所有值。为什么我的自定义HashMap类没有正确填充put?

HashMap表中值的图片。注意使用自定义HashMap类与直接使用HashMap时的区别。并非所有看跌期权值都存在,表格中存在差距。

扩展HashMap的自定义HashMap类

Custom class HashMap

Java HashMap

Using standard HashMap

1 个答案:

答案 0 :(得分:1)

最佳猜测:在getUpdateMode()中,地图的声明类型有一些超类,而不是CaseInsensitiveMap,或者传递给get()的值未声明为{{ 1}}。在任何一种情况下,它都将调用String HashMap版本的get(),而不是你的覆盖,它不会小写字符串因此失败,因为当存储的密钥为{{时它正在寻找"UpdateMode" 1}}。

这是因为您覆盖"updatemode"实际上不是覆盖,因为它声明的参数类型不同。 get()被声明为Map.get(),而不是Object,并且对其进行任何覆盖必须执行相同操作。将您的K覆盖更改为:

get()

如果您在每个覆盖上都使用了public T get(Object key) { if (!(key instanceof String)) { return null; } return super.get(((String) key).toLowerCase()); } 注释,那么您可能会收到编译器警告,告诉您这一点。

相关问题