首页 > 解决方案 > 插入HashMap后修改key对象

问题描述

我从 Excel 中读取了一个表格并将数据传递到一个搭扣地图中。但是,看起来 key 中使用的元素之一在插入后被覆盖了。我无法弄清楚出了什么问题。如果有人可以帮助我,我将不胜感激。

//资产城市类定义

public class AssetCity{
    public int asset;
    private int city; 
//constructors
//setters
// hashCode and Equals methods

在主函数中,我首先阅读了 excel 表并创建了我的地图。

XSSFSheet _pi = myWorkbook.getSheet("pi"); //get the sheet              
Map<AssetCity, Integer> pi = new HashMap<AssetCity, Integer>(); //create map            
    for(int i = _pi.getFirstRowNum() + 1 ; i <= _pi.getLastRowNum(); i++){              
        AssetCity pair = new AssetCity();   
        Row ro = _pi.getRow(i); //get each row
    for(int j = ro.getFirstCellNum()+1; j <= ro.getLastCellNum()-1;  j++) {
    Cell ce = ro.getCell(j); //go through each column 
    pair.setAssetCity(i, j); //create the key that will be inserted
        int val = (int) ce.getNumericCellValue(); // get the cell value                      
      // System.out.println(pair.toString()+ " "+ val);
    pi.put(pair, val); // insert into the map
        }                       
}

当我System.out.println(pair.toString()+ " "+ val);在插入操作之前使用时,我得到的结果如下所示,这是正确的,并且与我在 Excel 中的值匹配。

asset_city [asset=1, city=1] 0

asset_city [asset=1, city=2] 0

asset_city [asset=1, city=3] 0

.....

asset_city [asset=5, city=3] 1

asset_city [asset=5, city=4] 0              

现在,在我完成 for 循环之后,我迭代了地图中的所有元素。

Iterator<Map.Entry<AssetCity,Integer>> itr1 = pi.entrySet().iterator();
    while(itr1.hasNext())
        {
          Map.Entry<AssetCity,Integer> entry = itr1.next();                 
                  System.out.println(entry.getKey().toString() + " = " + entry.getValue());

现在,如您所见,键中的城市值看起来都一样。

asset_city [asset=2, city=4] = 0

asset_city [asset=3, city=4] = 0

asset_city [asset=4, city=4] = 0

asset_city [asset=5, city=4] = 0

asset_city [asset=1, city=4] = 0

asset_city [asset=2, city=4] = 1
asset_city [asset=3, city=4] = 0

asset_city [asset=4, city=4] = 0

asset_city [asset=1, city=4] = 0

asset_city [asset=2, city=4] = 0

asset_city [asset=3, city=4] = 1

asset_city [asset=1, city=4] = 0

asset_city [asset=2, city=4] = 0

asset_city [asset=1, city=4] = 1

asset_city [asset=5, city=4] = 0

asset_city [asset=4, city=4] = 0

asset_city [asset=5, city=4] = 0

asset_city [asset=3, city=4] = 0

asset_city [asset=4, city=4] = 1

asset_city [asset=5, city=4] = 1

标签: javahashmap

解决方案


AssetCity您正在为一行中的每个单元格覆盖同一对象中的数据。

要修复,AssetCity在内循环而不是外循环内声明和初始化您的对象。


推荐阅读