2016-08-27 2 views
-3

Ich habe diesen Code. Wenn ich ArrayList lösche, Werte in HashMap auch klar. Wie kann ich Daten speichern?Hashmap klare Werte

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

Wenn ich citiesList.clear(); alle Werte löschen, aber Schlüssel immer noch „lebendig“.

Antwort

1

Dies ist, weil sie die gleiche Referenz im Speicher haben.

Versuch dies zu tun:

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

Aber wenn das, was Sie wirklich ist es aus dem hashmap zu entfernen, werden Sie cities.remove(countryTitle) statt nur das Feld von Städten Clearing verlangen.