ssantonov ssantonov - 3 months ago 13
Android Question

Hashmap clear values

I have this code. When i clear

ArrayList
, values in
HashMap
clear too. How can i save data?

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();
}
}


When I use
citiesList.clear();
all values are clearing, but keys still "alive".

Answer

This is because they have the same reference in memory.

Try doing this:

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

But, if what you really want is to remove it from the hashmap, you'll have to call cities.remove(countryTitle) instead of only clearing the array of cities.