Order of items in HashSet not correct

前端 未结 3 1461
终归单人心
终归单人心 2021-01-28 12:13

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 s         


        
相关标签:
3条回答
  • 2021-01-28 12:37

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

    0 讨论(0)
  • 2021-01-28 12:39

    Use LinkedHashSet instead, with predictable iteration order.

    see docs here

    0 讨论(0)
  • 2021-01-28 12: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();
    }
    
    0 讨论(0)
提交回复
热议问题