问题
As an exercise I am developing a simple notes application. Obviously the notes have to be saved persistently so I have the following method:
public static void saveNotesPersistently() {
SharedPreferences.Editor editor = sharedPreferences.edit();
HashSet<String> titleSet = new HashSet<String>();
HashSet<String> contentSet = new HashSet<String>();
for (int i = 0; i < Library.notes.size(); i++) {
String title = (Library.notes.get(i).title == null) ? "No title" : Library.notes.get(i).title;
Log.d("Checks", "Saving note with title: " + title);
String content = (Library.notes.get(i).content == null) ? "No content yet" : Library.notes.get(i).content;
titleSet.add(title);
contentSet.add(content);
}
Log.d("Checks", "Saving title set: " + titleSet);
editor.putStringSet("noteTitles", titleSet);
editor.putStringSet("noteContents", contentSet);
editor.commit();
}
The strange thing is that the order of the note titles in the first Log is different from the order of the note titles in the second Log. Apparently something is going wrong in titleSet.add(title)
. I have no idea why though. Does anybody know what's happening here?
EDIT:
So I found out that it is because HashSet is not ordered. This presents me with another problem though, since I'm loading the notes like this:
Set<String> noteTitles = sharedPreferences.getStringSet("noteTitles", null);
Set<String> noteContents = sharedPreferences.getStringSet("noteContents", null);
Now the order is correct in saving, but it's wrong again after loading. Unfortunately there isn't something like sharedPreferences.getLinkedHashSet()
, so what could I do then?
回答1:
As requested, here is an example of serializing using a JSONArray.
Store the data:
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("jsonArray", new JSONArray(list).toString());
editor.commit();
Retreive the data:
try {
JSONArray jsonArray = new JSONArray(sharedPreferences.getString(
"jsonArray", null));
// jsonArray contains the data, use jsonArray.getString(index) to
// retreive the elements
} catch (JSONException e) {
e.printStackTrace();
}
回答2:
Use LinkedHashSet
instead, with predictable iteration order.
see docs here
回答3:
HashSet
provides no guarantees on the order of the elements. Consider using a TreeSet
if you need the elements to be ordered.
来源:https://stackoverflow.com/questions/18836109/order-of-items-in-hashset-not-correct