Order of items in HashSet not correct

喜夏-厌秋 提交于 2019-12-02 11:40:49

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

Store the data:

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

Retreive the data:

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

Use LinkedHashSet instead, with predictable iteration order.

see docs here

HashSet provides no guarantees on the order of the elements. Consider using a TreeSet if you need the elements to be ordered.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!