2

Can't figure it out why set.addAll is adding my list with the orders switched. (still my set is declared as LinkedHashSet)

The code is about getting a Set-List from SharedPreferences, convert it into an ArrayList, add one item to list and then add the whole list to Set.

The code looks something like this:

 Set<String> set = new LinkedHashSet<String>();
 List<String> stringList = new ArrayList<String>();

 ///

 set = getSharedPrefSet("mySet");
 stringList = new ArrayList<String>(set);
 stringList.add(message);
 set.addAll(stringList);  //this messes up my order
 saveSharedPrefSet("mySet", set);

The first two strings add correctly (as I debugged it) but the third switches position with the second one.

Output:

enter image description here

The getSharedPrefSet function:

Set getSharedPrefSet (String key) {
    sharedPrefs = this.getSharedPreferences("myPreferences", Context.MODE_PRIVATE);

    return sharedPrefs.getStringSet(key, null);
}

Workaround

One solution can be found at How can write code to make sharedpreferences for array in android?

Community
  • 1
  • 1
Vlad.mir
  • 685
  • 1
  • 10
  • 28

1 Answers1

2

I can see what your problem is! Even though you're initialising set as a LinkedHashSet which is supposed to preserve the order of items, look at this line, after that:

set = getSharedPrefSet("mySet");

Now, I don't see the getSharedPrefSet method implementation here, but looking at the screenshot you provided I can see that set is now HashSet. So the method must have returned the HashSet and thus you're losing the order you want because HashSet does not preserve it.

From the docs of LinkedHashSet:

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.

So what you need to do is to actually take a different approach here, because no matter what you initialise your set variable with, it's gonna get overwritten by whatever the getSharedPrefSet method returns (so initialisation is obsolete anyway). Find another way around it, sharedPrefs.getStringSet apparently returns a normal HashSet.

Vucko
  • 7,371
  • 2
  • 27
  • 45
  • Thanks for answer, I was looking into it and I don't think you can get anything else than HashSet from SharedPreferences .getStringSet. – Vlad.mir Jan 11 '17 at 16:51
  • Yeah, I thought so... Well then you'll need to find some workaround cause this is not gonna work :) Consider accepting the answer cause I think we cracked what the issue was. – Vucko Jan 11 '17 at 17:16