java - 插入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
解决方案
AssetCity
您正在为一行中的每个单元格覆盖同一对象中的数据。
要修复,AssetCity
在内循环而不是外循环内声明和初始化您的对象。
推荐阅读
- google-bigquery - BigQuery 定价:记录列的查询数据大小(成本)计算
- swift - 从函数中获取单个结果
- machine-learning - 如何更改 Xgboost 中的功能重要性
- python - 使用 JiTCDDE 将解决方案限制为正值
- python - 是否有用于事件驱动的 Kafka 消费者的 Python API?
- c# - 使用显式命名空间规范序列化 SOAP 消息
- mysql - mysql 命令用于列出表中的所有行?
- abap - 更改目的地的路径前缀
- blogger - b:if 选择同时适用于 http 和 https
- ios - NSLayoutManager:如何在只有可渲染字形的地方填充背景颜色