作为练习,我正在开发一个简单的笔记应用程序。显然,笔记必须持久保存,所以我有以下方法:
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();
}
奇怪的是,第一个日志中注释标题的顺序与第二个日志中注释标题的顺序不同。显然有些事情出了问题titleSet.add(title)
。我不知道为什么。有人知道这里发生了什么吗?
编辑:
所以我发现这是因为 HashSet 没有排序。这给我带来了另一个问题,因为我正在加载这样的笔记:
Set<String> noteTitles = sharedPreferences.getStringSet("noteTitles", null);
Set<String> noteContents = sharedPreferences.getStringSet("noteContents", null);
现在保存的顺序是正确的,但是加载后又出错了。不幸的是,没有类似的东西sharedPreferences.getLinkedHashSet()
,那我该怎么办?