android - Add items to a Set<String> in proper order Java -
i creating song playback app. have set keep in sharedpreferences. want add , remove file names it, , keep them in same order added them in example:
recentsp = getsharedpreferences("recentkey", context.mode_private); recent = recentsp.getstringset("recent", recent); recentedited = recent; if (recentedited.contains(string) { recentedited.remove(string); log.i(tag, "recent exists, removing song"); sharedpreferences.editor editor = recentsp.edit(); editor.clear(); editor.putstringset("recent", recentedited); editor.commit(); } recentedited.add(string); log.i(tag, "adding song recent"); sharedpreferences.editor editor = recentsp.edit(); editor.clear(); editor.putstringset("recent", recentedited); editor.commit();
but problem arises when view these in listview. want them in order add them can have played section, don't move @ all, or maybe end in beginning. seems random. missing something?
edit:
i check make sure sharedpreferences not null doing in initialization step...
edit:
even using linkedhashset still don't proper ordering. call if sharedpreferences null, i'm not sure how make sure using linkedhashset.
recentsp = getsharedpreferences("recentkey", context.mode_private); recent = recentsp.getstringset("recent", null); if (recent == null) { recent = new linkedhashset<string>(); sharedpreferences.editor editor = recentsp.edit(); editor.clear(); editor.putstringset("recent", recent); editor.commit(); }
if looking implementation of set
interface preserves insertion order, switch hashset
to: linkedhashset
. of standard set
behavior remains intact, addition of insertion-order iteration.
from associated javadoc:
hash table , linked list implementation of set interface, predictable iteration order. implementation differs hashset in maintains doubly-linked list running through of entries. linked list defines iteration ordering, order in elements inserted set (insertion-order). note insertion order not affected if element re-inserted set. (an element e reinserted set s if s.add(e) invoked when s.contains(e) return true prior invocation.)
this implementation spares clients unspecified, chaotic ordering provided hashset, without incurring increased cost associated treeset. can used produce copy of set has same order original, regardless of original set's implementation
Comments
Post a Comment