方法put(Integer,Integer)在Map <integer,integer>类型中不适用于参数(String,Integer)

时间:2017-07-03 10:28:32

标签: java dictionary

我已经编写了一些代码,这些代码将获取余额图中每个条目的键,然后如果它与钱包名称映射中的键匹配,则将余额映射中的值替换为钱包的相应名称。 / p>

没有问题代码,它按预期工作,见下文:

钱包名称图:

purseNames = {497=ASC, 64339=Football, 488=BC, 169=Pre-pay, 170=Cafeteria, 171=Lettings, 172=Dinner}

示例余额数据:

balances = {497=-7000, 64339=0, 169=-500, 170=0, 172=0}

我的代码:

// For every account in the List of Accounts
for (AccountGridRow accountGridRow : accountGridRows) {

        // The original balances
        Map<Integer, Integer> balances = accountGridRow.getBalances();

        // Go through and match up the ID's with their corresponding names
        for (int i = balances.size() - 1; i >= 0; i--){
            Object balanceKey = balances.keySet().toArray()[i];
            for (int j = 0; j < purseMap.size(); j++) {
                Object purseKey = purseMap.keySet().toArray()[j];
                if (purseKey.equals(balanceKey)){
                    String purseName = purseMap.values().toArray()[j].toString();

                    // Take the old balance value and put it in the new map, 
                    // with the new name key. 
                    Integer obj = balances.remove(balanceKey);
                    balances.put(purseName, obj);
                    break;
                    }
            }
        }

我的结果:

balances = {ASC=-7000, Dinner=0, Football=0, Cafeteria=0, Pre-pay=-500}

问题:

我需要能够取代&#39;余额&#39;对于每个帐户,我的结果集中有新的余额,但是我不能这样做,因为地图类型不同。 &#39; AccountGridRow&#39;上课期望:

Map<Integer, Integer>

但是,我的新修改后的地图位于以下类型:

Map<String, Integer> 

我无法更改AccountGridRow所期望的类型,因为它正被代码中的许多其他位置使用。

梦幻般的结果:

这将最终序列化为JSON,示例帐户条目,位于:

"accounts" 
[
  {
"accountId": 1123,
"accountNum": "1009",
"lastname": "Bar",
"firstname": "foo",
"address": "91 Awesome St, Awesomeville, Somewheresota, 45251",
"class": "Tigers",
"status": "Active",
"balances": {

    // replace with the balances, with the purse names instead of purse ID. 

},
"yearRegistered": "2005"
  }
]

有没有人有办法解决这个问题?我试图通过替换行来使用newBalance映射:

balances.put(purseName, obj);

Map<String, Integer> newBalances = new HashMap<>();
newBalances.put(purseName, obj);

但我无法弄清楚如何用“新平衡”替换余额。没有得到“不适用于论点”的说法。错误。

3 个答案:

答案 0 :(得分:0)

如果我理解正确,你想将String转换为整数? 这个答案似乎很简单,但你不能使用

balances.put(new Integer(purseName), obj);

答案 1 :(得分:0)

只需编写一个转换方法,将String值转换为int并将该方法应用于每个用于键的值, 还要注意可能导致异常的格式错误的字符串。您可以为这些情况定义默认值:

int convertToInt(String value) { 
try {  
   return Integer.parseInt(value);  
} catch(NumberFormatException nfe) {  
  // Log exception.
  return 0;
  }  
}

答案 2 :(得分:0)

我在这里问到的另一个问题就是这个问题提供了答案:

Can I override a Map<Integer, Integer> with Map<String, Integer>?