hashset重新排序信息,我能做什么不被重新排序?

vd2z7a6w  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(241)

我有疑问和一个问题,我试图解决这个笔记应用程序,我发现谷歌,这是非常简单的,所以我(一个初学者)去尝试它的一些东西。每次我保存一些笔记,关闭应用程序,重新启动应用程序,它会按字母顺序重新组织笔记,这是我不想要的。我知道set和arraylist是不同的,因为set不会重复元素,但是arraylist会。同时set不能保证调用时的顺序。
问题是:如何解决这个固有的排序问题?
我尝试将hashset的内容切换到arraylist,但是方法putstringset需要在其参数中设置一个集合,而arraylist则不是。
下面的代码可以工作(不会崩溃或任何其他问题),但不能按我所希望的那样工作。
我在主活动中有这个部件代码

SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.tanay.thunderbird.deathnote", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);

// a lot of other things here

    if (set == null) {
                notes.add("Example Note");
            } else {
                notes = new ArrayList<>(set);         // to bring all the already stored data in the set to the notes ArrayList
            }

在我的记事本上

Intent intent = getIntent();
    noteID = intent.getIntExtra("noteID", -1);

    if (noteID != -1) {
        editText.setText(MainActivity.notes.get(noteID));
    } else {
        MainActivity.notes.add("");                // as initially, the note is empty
        noteID = MainActivity.notes.size() - 1;
        MainActivity.arrayAdapter.notifyDataSetChanged();
    }
//other things here
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                MainActivity.notes.set(noteID, String.valueOf(s));
                MainActivity.arrayAdapter.notifyDataSetChanged();

                SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.tanay.thunderbird.deathnote", Context.MODE_PRIVATE);
                HashSet<String> set = new HashSet<>(MainActivity.notes);
                sharedPreferences.edit().putStringSet("notes", set).apply();
            }
o4tp2gmn

o4tp2gmn1#

如果你想保持笔记的顺序, Array 或者 List 是比使用 Set .
将此存储到 SharedPreferences ,您可以从共享首选项中引用put和get字符串数组
此问题的答案解释如下:
jsonify列表并解析它。
用分隔符连接所有字符串并将其拆分。

相关问题