Good evening.

String[] tasks = new String[]{<элементы>}; Set<String> sTasks = new HashSet<String>(Arrays.asList(tasks)) 

Put in SharedPreferences:

 SharedPreferences settings=context.getSharedPreferences("settings", context.MODE_PRIVATE); SharedPreferences.Editor editor = settings.edit(); if(isClearing){ editor.clear(); }else { editor.putStringSet("Имя1", sTasks); } editor.commit(); } 

We get:

 Set<String> tasks2 = (HashSet<String>)this.getSharedPreferences("settings", Context.MODE_PRIVATE).getAll().get("Имя1"); 

Items are confused. Where did I go? :(

UPD: It gives an error on trying to get from the settings in LinkedHashSet:

 LinkedHashSet<String> task = (LinkedHashSet<String>)this.getSharedPreferences(MainActivit‌​y.STORAGE_NAME, Context.MODE_PRIVATE).getAll().get(name); 

Says that "ClassCastException: java.util.HashSet cannot be cast to java.util.LinkedHashSet".

I do not understand where he found the hash.

    2 answers 2

    HashSet does not guarantee the preservation of the order of elements. To remove duplicate items while preserving their order, you need to use LinkedHashSet .

    Example :

     String[] tasks = new String[]{"e", "a", "c", "b", "c", "d", "a", "a"}; Set<String> sTasks = new HashSet<String>(Arrays.asList(tasks)); System.out.println(sTasks); // [a, b, c, d, e] Set<String> sTasks1 = new LinkedHashSet<String>(Arrays.asList(tasks)); System.out.println(sTasks1); // [e, a, c, b, d] 

    Preserving the order of elements in SharedPreferences more complicated . You can save the Set, and SharedPreferences does not know whether it is necessary to preserve the order of the elements, therefore, generally speaking, saving the lines will not work. You can solve this problem in the following ways:

    • loop through the resulting LinkedHashSet , storing the values ​​into strings of the format "value_" + i and getting it back in the same way.
    • convert the set to a JSON string and save it. Then get this string and convert back to collection.
    • Completed the question. - keltkelt
    • In general, I found such a topic. stackoverflow.com/questions/18779331/… . And it seems SharedPreferences simply do not guarantee the order of the elements. I do not understand why they did it like this ... - keltkelt

    In general, I found such a topic.
    https://stackoverflow.com/questions/18779331/android-hashset-cannot-be-cast-to-linkedhashset
    SharedPreferences work with HashSet, so you need to use ArrayList or Json to preserve order.