• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps Help with putStringSet and getStringSet method

Anza87

Newbie
I understand now methods putString and getString for saving one string for example,
but I want to save some array of strings, for example 5 strings. I
found this two methods(putStringSet, getStringSet), but I don't know
how to fill Set<String> with strings. Can anybody help me? tnx:)
public abstract SharedPreferences.Editor putStringSet (String key, Set<String> values)

public abstract Set<String> getStringSet (String key, Set<String> defValues)




http://developer.android.com/refere...lang.String, java.util.Set<java.lang.String>)
 
You can use the following code:

Code:
Set<String> defValues = new HashSet<String>();

defValues.add("string 1");
defValues.add("string 2");
defValues.add("string 3");
 
Thanks. I save now in my project some strings in HashSet, like you show me. What is now the easiest way to read this strings out from HashSet like defValues, for example?
 
The Set interface doesn't provide a method for random accessing of elements. Worse than that, the interface doesn't guarantee anything about the order of the elements. So, you can use the following code:

Code:
int i = 0;
for(String s: defValues) {
    if (i == 1) {
        // do something with the second element
     
        break;
    } 
    i++; 
}
but that doesn't mean that you will get the string that you've inserted second. You could use the LinkedHashSet implementation, which provides a predictable iteration order, but you would still need to access a random element with the above cumbersome way.

If random access is important for you, I suggest that you hold your Strings in a List container. Create a Set out of the List, when you need to use it. Be warned that duplicate elements are allowed in a List, but not in a Set.
 
Back
Top Bottom