ssantonov ssantonov -4 years ago 174
Android Question

Hashmap clear values

I have this code. When i clear

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

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


public void parseFrom() {
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);
countryTitle = jsonObject.getString("countryTitle");
} catch (JSONException e) {

When I use
all values are clearing, but keys still "alive".

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download