无法从传入的密钥中找到散列映射中的关联值

Mel*_*nda 0 java

我正在使用Eclipse项目中的一些现有代码.在下面调用的方法中cardTypeForPbfValue(),我找不到密钥,HashMap即使我可以在调试代码时看到它.该pbfValueMap填充如下:

[1=ATM, 2=DEBIT, 3=CREDIT, 4=PAYROLL]
Run Code Online (Sandbox Code Playgroud)

我不知道为什么CREDIT当我在下面传递值3时,我无法得到相关的值cardTypeForPbfValue().我实际上得到的价值NULL.

任何帮助/方向将不胜感激.

这是我正在使用的代码:

public static enum CardType {
    CREDIT(3),
    ATM(1),
    DEBIT(2),
    PAYROLL(4);
    CardType(int pbfValue) {
        this.pbfValue = (short) pbfValue;
    }

    public static HashMap<Short, CardType>  pbfValueMap = new HashMap<Short, CardType>();
    static {
        for (CardType cardType : CardType.values()) {
            short value = cardType.pbfValue;
            pbfValueMap.put(cardType.pbfValue, cardType);
        }
    }

    public static CardType **cardTypeForPbfValue**(int pbfValue) {
        CardType returnValue = pbfValueMap.get(pbfValue);
        if (returnValue == null) {
            returnValue = DEBIT;
        }
        return returnValue;
    }

    public short    pbfValue;
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

你正在查找Integer,但是你把它Short放进了地图.试试这个:

public static CardType cardTypeForPbfValue(int pbfValue) {
    Short shortPbfValue = (short) pdbValue;
    CardType returnValue = pbfValueMap.get(shortPbfValue);
    ...
}
Run Code Online (Sandbox Code Playgroud)

更好的是,停止int在任何地方使用(或停止使用short地图) - 只需要在您想要使用的类型中保持一致.