如何不对 HashSet 值进行排序并允许重复?

how to not sort a HashSet values and allow duplicate?

我正在开发 Android 项目,我想将 arrayList 值保存到 sharedpreferences

我不想对列表中的重复值进行排序或删除

我想要 arrayList 中的确切数据保存在 HashSet

例如这是我的 arrayList 输出:

D/waitingList﹕ [a, b, c, a, a, aa, cc]

但是当我将它保存在 HashSet 中时,它会排序

D/setWaiting﹕ [aa, a, b, cc, c]

并在 sharedpreferences xml 文件中这样

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <int name="count_games" value="0" />
    <set name="setCurrent" />
    <set name="setWaiting">
        <string>a</string>
        <string>aa</string>
        <string>b</string>
        <string>c</string>
        <string>cc</string>
    </set>
</map>

我必须按照 arrayList 中的方式对所有内容进行排序

这是我的代码:

public void saveArrayList(Context mContext, ArrayList<String> currentList, ArrayList<String> waitingList, int count)
    {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(mContext);
        SharedPreferences.Editor edit = pref.edit();

        HashSet<String> setCurrent = new HashSet<String>();
        setCurrent.addAll(currentList);
        Log.d("setCurrent",setCurrent.toString());
        Log.d("currentList",currentList.toString());

        HashSet<String> setWaiting = new HashSet<String>();
        setWaiting.addAll(waitingList);
        Log.d("setWaiting",setWaiting.toString());
        Log.d("waitingList",waitingList.toString());


        edit.putStringSet("setWaiting", setWaiting);
        edit.putStringSet("setCurrent", setCurrent);

        edit.putInt("count_games", count);

        edit.commit();


    }

根据定义,一个 Set 不能有重复的值,所以你不能做你想做的事。

此外,HashSet 不保留顺序,如果你想要有序集合,你可以使用 LinkedHashSet 保留插入顺序。