2013-05-08 14 views
0

我正在使用我的Eclipse项目中的一些现有代码。在以下称为cardTypeForPbfValue()的方法中,即使我在调试代码时可以看到它,但仍无法找到HashMap中的密钥。从传入的密钥中找不到散列表中的关联值

[1=ATM, 2=DEBIT, 3=CREDIT, 4=PAYROLL] 

我不知道为什么,当我路过的值为3以下cardTypeForPbfValue()我不能得到的CREDIT关联的值:pbfValueMap如下填充。我实际上获得了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; 
} 
+0

它是int,先把它缩短。 – 2013-05-08 17:41:49

回答

6

你正在寻找了一个Integer,但你把Short到地图。试试这个:

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

更重要的是,停止使用int无处不在(或停止使用short的地图) - 只是在你想使用的类型一致。

+0

谢谢您的回复。试图修复现有的代码,我一直在寻找这种方式太久了。 – Melinda 2013-05-08 17:51:09

1

我猜的是你正在使用Short作为关键类型,而你正在寻找HashMap的值与Integer键。这就是为什么你没有得到输入键的关联值。为了解决这个问题您cardTypeForPbfValue方法应该是这样的:

public static CardType cardTypeForPbfValue(short pbfValue) 

何地,你叫cardTypeForPbfValueshort类型的参数传递给它的方法。例如:

short s = 1; 
CardType cType = cardTypeForPbfValue(s); 
+0

非常感谢。我很欣赏这个快速回复。这样看太久了。 – Melinda 2013-05-08 17:50:31