首页 > 解决方案 > 对象不添加到另一个对象数组列表

问题描述

我有 2 个对象。WeatherStationWeatherReading

我有一个WeatherReading对象数组列表WeatherStation,我试图添加到:

气象站类:

public ArrayList<WeatherReading> readings = new ArrayList<WeatherReading>();

public WeatherStation(int id, double lat, double lon, String name) {
        super();
        this.id = id;
        this.lat = lat;
        this.lon = lon;
        this.name = name;
}

readings我通过使用addReading()哪个在WeatherStation类中添加到数组列表中。

public boolean addReading(WeatherReading reading) {
        this.readings.add(reading);
        return true;
}

在另一个名为Generator我的类中,我尝试将这些读数添加到这个数组列表中。

public static void addReadings(ArrayList<WeatherStation> stations, String[] weatherData) {
        for(int i = 1; i < weatherData.length; i++) {
            WeatherReading currentReading = genReading(weatherData[i]);
            WeatherStation currentStation = genStation(weatherData[i]);
            if(currentReading.getId() == currentStation.getId()) {
                currentStation.addReading(currentReading);
            }
        }
    }

尽管完成此操作后,我尝试打印出我的WeatherStations,但没有将读数添加到数组列表中:

WeatherStation [id=3226, lat=54.57, lon=-2.42, name=WARCOP (3226), readings=[]]
WeatherStation [id=3482, lat=52.651, lon=0.569, name=MARHAM (3482), readings=[]]
WeatherStation [id=3227, lat=54.68, lon=-2.45, name=GREAT DUN FELL (3227), readings=[]]
WeatherStation [id=3740, lat=51.5031, lon=-1.9924, name=LYNEHAM (3740), readings=[]]
WeatherStation [id=3230, lat=55.28, lon=-2.28, name=REDESDALE CAMP (3230), readings=[]]
WeatherStation [id=3743, lat=51.201, lon=-1.805, name=LARKHILL (3743), readings=[]]
WeatherStation [id=3488, lat=52.949, lon=1.127, name=WEYBOURNE (3488), readings=[]]

如何确保我添加到WeatherReading对象数组列表并且不让数​​组列表为空

标签: javaarraylist

解决方案


推荐阅读