Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can somebody explain how SharedPreferences stores a string set

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)?

like image 668
Moshe Stauber Avatar asked Feb 17 '26 08:02

Moshe Stauber


1 Answers

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.

like image 117
daxgirl Avatar answered Feb 19 '26 00:02

daxgirl