我从Excel中读取一个表并将数据传递到hasp映射中。但是,看起来插入后,键中使用的元素之一会被覆盖。我无法弄清楚出了什么问题。如果有人可以帮助我,我真的很感激。// AssetCity类定义public class AssetCity{ public int asset; private int city; //constructors//setters// hashCode and Equals methods在main函数中,我首先阅读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] 0asset_city [asset=1, city=2] 0asset_city [asset=1, city=3] 0.....asset_city [asset=5, city=3] 1asset_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] = 0asset_city [asset=3, city=4] = 0asset_city [asset=4, city=4] = 0asset_city [asset=5, city=4] = 0asset_city [asset=1, city=4] = 0asset_city [asset=2, city=4] = 1asset_city [asset=3, city=4] = 0asset_city [asset=4, city=4] = 0asset_city [asset=1, city=4] = 0
2 回答

大话西游666
TA贡献1817条经验 获得超14个赞
因为AssetCity对是在内部循环之外创建的,所以在“j”循环的每次迭代中都会更新该创建的对。
也许你想在内部循环中创建一个AssetCity对的新实例,就像下面的代码片段一样。这意味着它是内部'j'循环的每次迭代的新实例。
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++){ 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 AssetCity pair = new AssetCity(); 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 } }
添加回答
举报
0/150
提交
取消