有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓以适当的顺序将项目添加到集合<String>

我正在创建一个歌曲播放应用程序。我有一套,我保存在共享参考资料中。我想从中添加和删除文件名,并保持它们的顺序与我在中添加它们的顺序相同,例如:

recentsp = getSharedPreferences("recentkey", Context.MODE_PRIVATE);

    recent = recentsp.getStringSet("recent", recent);
    recentedited = recent;

    if (recentedited.contains(string) {
        recentedited.remove(string);
        Log.i(TAG, "Recent exists, removing song");
        SharedPreferences.Editor editor = recentsp.edit();
        editor.clear();
        editor.putStringSet("recent", recentedited);
        editor.commit();
    }

        recentedited.add(string);
    Log.i(TAG, "adding song to recent");
        SharedPreferences.Editor editor = recentsp.edit();
        editor.clear();
        editor.putStringSet("recent", recentedited);
        editor.commit();

但当我在ListView中查看这些时,问题就出现了。我希望他们按照我添加他们的顺序,这样我就可以有一个最近播放的部分,但有时他们根本不移动,或者可能他们在一开始就结束了。这似乎是随机的。我错过什么了吗

编辑:

我检查以确保SharedReferences不为null,方法是在初始化步骤中执行此操作

编辑:

即使使用LinkedHashSet,我仍然没有得到正确的排序。我只在SharedReferences为null时调用它,因此我不确定如何确保使用LinkedHashSet

        recentsp = getSharedPreferences("recentkey", Context.MODE_PRIVATE);
    recent = recentsp.getStringSet("recent", null);
    if (recent == null) {

        recent = new LinkedHashSet<String>();
        SharedPreferences.Editor editor = recentsp.edit();
        editor.clear();
        editor.putStringSet("recent", recent);
        editor.commit();
    }

共 (3) 个答案

  1. # 1 楼答案

    如果您正在寻找保留插入顺序的Set接口的实现,请从HashSet切换到:LinkedHashSet。所有标准的Set行为都保持不变,添加了插入顺序迭代

    从相关的JavaDoc:

    Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

    This implementation spares its clients from the unspecified, generally chaotic ordering provided by HashSet, without incurring the increased cost associated with TreeSet. It can be used to produce a copy of a set that has the same order as the original, regardless of the original set's implementation

  2. # 2 楼答案

    也许只需要使用ArrayList而不是Set——看起来您已经有了确保删除和添加项目(如果该项目已经在集合中)的代码——该模式应该与ArrayList一起使用

    如果您需要代码将列表序列化为首选项,这个老问题有一个例子Save ArrayList to SharedPreferences,或者使用类似GSON的东西来存储和检索Store a List or Set in SharedPreferences

  3. # 3 楼答案

    I have a Set that I keep in SharedPreferences. I want to add and remove file names from it, and keep them in the same order

    这是不可能的。您不控制Set实现,并且不需要订购Set。你的选择是:

    1. 不要担心订单,或

    2. 不要将字符串集与SharedPreferences一起使用,而是将值存储在单个字符串中(例如,编码为JSON),或

    3. 不要使用SharedPreferences,而是使用其他一些数据存储选项(例如SQLite数据库、JSON文件)