WeatherStation类readings ArrayList添加WeatherReading后为空的解决方法
问题分析与解决方案:WeatherReading无法添加到WeatherStation的readings列表
我一眼就看出问题出在哪了——你在addReadings方法里踩了一个很容易犯的小坑:你每次循环都创建了一个全新的WeatherStation对象,而不是操作传入的stations列表里的已有站点。
具体来说,你调用genStation(weatherData[i])生成了一个临时的currentStation,然后把读数加到这个对象里,但这个临时对象根本不在你最后要打印的stations列表中。所以原列表里的站点自然还是空的readings——因为你从来没往它们里面加过东西。
修复方案
核心思路是:从传入的stations列表中找到对应ID的站点,再把读数加进去,而不是每次新建站点。
这里给你修改后的代码,还加了辅助方法和调试提示,方便你排查问题:
public static void addReadings(ArrayList<WeatherStation> stations, String[] weatherData) { for(int i = 1; i < weatherData.length; i++) { WeatherReading currentReading = genReading(weatherData[i]); // 从传入的stations列表中查找对应ID的站点,而非新建 WeatherStation targetStation = findStationById(stations, currentReading.getId()); if(targetStation != null) { targetStation.addReading(currentReading); // 可选:调试用,确认读数添加成功 System.out.println("已为站点[" + targetStation.getId() + "]添加读数"); } else { // 可选:处理找不到站点的情况,避免静默失败 System.out.println("警告:未找到ID为" + currentReading.getId() + "的站点,跳过该读数"); } } } // 辅助方法:根据ID从stations列表中匹配对应的站点 private static WeatherStation findStationById(ArrayList<WeatherStation> stations, int targetId) { for(WeatherStation station : stations) { // 确保WeatherStation类有getId()方法来获取id字段 if(station.getId() == targetId) { return station; } } return null; }
额外注意事项
- 给WeatherStation补充getId()方法:你原来的代码里
WeatherStation有id字段,但没有暴露getter,需要补充这个方法:public int getId() { return this.id; } - 检查ID匹配逻辑:确认
genReading生成的WeatherReading的ID,确实和stations列表中存在的站点ID一致。如果ID不匹配,辅助方法会返回null,读数也加不进去,这时候调试日志会帮你快速定位问题。 - 移除多余判断:原来代码里的
if(currentReading.getId() == currentStation.getId())完全没必要——你新建的station和reading的ID可能一致,但这不是你要操作的目标站点。
这样修改后,你是往stations列表里的真实站点对象添加读数,打印的时候就能看到readings列表里的内容了。
内容的提问来源于stack exchange,提问作者user13914470
相关产品推荐
相关产品推荐

