I was trying to save a list of names in shared preferences and wanted to make use of the SharedPreferences putStringSet so that I won't need multiple key-value pairs.
I know a regular HashSet doesn't guarantee iteration order so I used a LinkedHashSet to maintain the iteration order as the order of insertion and saved that to shared preferences.
When retrieving the same String Set I also used a LinkedHashSet but the order was not the same as when originally inserted.
I solved the problem by just storing the names in a comma separated string then parsing that, so that's not my question.
I would like to know what SharedPreferences does to a set of strings so that it does not maintain the correct ordering (at least not the one I want)?
To answer your question in short it un-links your linked hash set by creating a simple HashSet from your values... from that point on - no links of order.
From source code:
public Editor putStringSet(String key, Set<String> values) {
synchronized (this) {
mModified.put(key,
(values == null) ? null : new HashSet<String>(values));
return this;
}
}
Thats why, like you did, if you want to preserve order you need to store as string with separators (you used coma) and then split the separator to get an array.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With