HashSet中的项目顺序不正确 [英] Order of items in HashSet not correct

查看:78
本文介绍了HashSet中的项目顺序不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为练习,我正在开发一个简单的Notes应用程序.显然,笔记必须永久保存,因此我有以下方法:

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

奇怪的是,第一个日志中注释标题的顺序与第二个日志中注释标题的顺序不同.显然在titleSet.add(title)中出了点问题.我不知道为什么.有人知道这里发生了什么吗?

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?

所以我发现这是因为HashSet没有排序.但是,这给我带来了另一个问题,因为我正在加载这样的注释:

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

现在保存时顺序是正确的,但是在加载后又是错误的.不幸的是,没有类似sharedPreferences.getLinkedHashSet()的东西,那我该怎么办?

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?

推荐答案

根据要求,下面是一个使用JSONArray进行序列化的示例.

As requested, here is an example of serializing using a JSONArray.

存储数据:

SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("jsonArray", new JSONArray(list).toString());
editor.commit();

检索数据

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

这篇关于HashSet中的项目顺序不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆