Why does SharedPreferences not support lists of Strings?

时间:2015-09-14 16:03:34

标签: android android-sharedpreferences

Why does SharedPreferences.Editor have a method putStringSet() but not a method putStringList()? This doesn't make any sense to me. My understanding (which could be wrong) is that SharedPreferences objects are stored internally using xml, and xml supports arrays.

I understand that a SharedPreference object is intended to be a simple object for small amounts of data, so you wouldn't want to have too many put methods, but I would have thought if you were going to have one of putStringSet() or putStringList(), putStringList() would be both more generally useful (a set can be saved as a list, but not vice-versa) and easier to implement. Can anyone explain this?

1 个答案:

答案 0 :(得分:2)

I am not an implementor of the source but if you think about it, the KV store that SharedPreferences are is pretty barebones. So you have putString() and you have put StringSet(). Using StringSet variants to save multiple strings put no constraints on the actual storage solution. i.e. if instead of an XML file it were a sqlite db, you could query the table for all values with the key and that type. Whatever way the sql engine ordered them would be taken as is. However if you had to maintain order a new structure that would impose onto all other data types would have to be introduced, like an order column. Even in XML this would require more storage and more complexity to denote that one is ordered and one is not.

It seems to me that as long as the SharedPreferences supports putString and putStringSet you can achieve both ordered and non ordered storage.

i.e.

String orderedString = TextUtils.join(mySafeDeliminator, myListOfStrings);
preferences.edit().putString("key", orderedString).apply();

....
String orderedReturnedString = preferences.getString("key");
List<String> listOfStrings = Arrays.asList(TextUtils.split(orderedReturnedString, mySafeDeliminator));