【问题标题】:Hashmap clear valuesHashmap 清除值
【发布时间】:2016-08-27 17:00:50
【问题描述】:

我有这个代码。当我清除ArrayList 时,HashMap 中的值也会清除。如何保存数据?

public class Stations extends AppCompatActivity {
    public static Map<String, ArrayList<String>> cities = new HashMap<>();

    ...

    public void parseFrom() {
        cities.clear();
        ArrayList<String> citiesList = new ArrayList<>();
        try {
            JSONObject jObject = new JSONObject(loadJSON());
            JSONArray jArray = jObject.getJSONArray("citiesFrom");
            String countryTitle = null;

            for (int i = 0; i < jArray.length(); i++) {
                JSONObject jsonObject = jArray.getJSONObject(i);
                if ((countryTitle != null) && (!countryTitle.equals(jsonObject.getString("countryTitle")))) {
                    cities.put(countryTitle, citiesList);
                    citiesList.clear();
                }
                countryTitle = jsonObject.getString("countryTitle");
                citiesList.add(jsonObject.getString("cityTitle"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

当我使用citiesList.clear();时,所有值都在清除,但键仍然“活动”。

【问题讨论】:

    标签: java android arraylist hashmap


    【解决方案1】:

    这是因为它们在内存中具有相同的引用。

    尝试这样做:

    cities.put(countryTitle, new ArrayList<String>(citiesList));
    

    但是,如果您真正想要的是从 hashmap 中删除它,则必须调用 cities.remove(countryTitle) 而不是只清除城市数组。

    【讨论】:

      猜你喜欢
      • 2013-11-20
      • 2014-02-22
      • 2021-08-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-25
      • 1970-01-01
      • 1970-01-01
      • 2015-04-09
      相关资源
      最近更新 更多