网站彩票做号,域名备案后怎样做网站,兼职刷客在哪个网站做,照片网站cms对于很多有搜索需求的功能#xff0c;一般需要展示下最近n次的历史搜索记录#xff0c;主要有以下几个功能点#xff1a;
最近搜索条目放在最前面#xff0c;最早的搜索记录放在最后。只记录最近n条数据#xff0c;如果超过n条搜索记录#xff0c;删除搜索时间最久远的记…对于很多有搜索需求的功能一般需要展示下最近n次的历史搜索记录主要有以下几个功能点
最近搜索条目放在最前面最早的搜索记录放在最后。只记录最近n条数据如果超过n条搜索记录删除搜索时间最久远的记录。没有重复的搜索项如果新搜索的关键字已存在则将该关键字提到最前面删除原位置关键字。可方便的持久化并可以通过读取持久化数据恢复原纪录历史。
基于以上这些条件不难看出这就是一个无重复数据的LRU stack本来以为java集合会有支持该需求的实现尝试了stack等集合类型发现不是很好弄最后还是采用list做一个吧简单方便。
Android版
public class SearchHistoryUtil {private LruStackUtil mLruStack null;public SearchHistoryUtil(int maxSize) {this.mLruStack new LruStackUtil(maxSize);}public void updateSearchHistorys(Context context, String keyWord) {SharedPreferences sharedPreferences context.getSharedPreferences(music_search_history,Activity.MODE_PRIVATE);String mKeys sharedPreferences.getString(keys, );mLruStack.reset();SharedPreferences.Editor editor sharedPreferences.edit();String[] tmpHistory mKeys.split(,);for (String i : tmpHistory) {mLruStack.push(i);}mLruStack.pushHead(keyWord);editor.putString(keys, mLruStack.getAll());editor.apply();}public static String getAllHistorys(Context context) {SharedPreferences sharedPreferences context.getSharedPreferences(music_search_history,Activity.MODE_PRIVATE);String mKeys sharedPreferences.getString(keys, );return mKeys;}public static void clearAll(Context context) {SharedPreferences sharedPreferences context.getSharedPreferences(music_search_history,Activity.MODE_PRIVATE);SharedPreferences.Editor editor sharedPreferences.edit();editor.clear();editor.apply();}
}public class LruStackUtil {ArrayListString stack null;private int size 0;public LruStackUtil(int size) {this.stack new ArrayListString();this.size size;}public void pushHead(String keyWord) {if (stack.remove(keyWord)) {stack.add(0, keyWord);return;}if (stack.size() this.size - 1) {stack.remove(stack.size() - 1);stack.add(0, keyWord);} else {stack.add(0, keyWord);}}public void push(String keyWord) {if (stack.contains(keyWord)){return;}if (stack.size() this.size - 1) {return;} else {stack.add(keyWord);}}public String getAll() {StringBuilder str new StringBuilder();for (int i 0; i stack.size(); i) {str.append(stack.get(i) ,);}return str.toString();}public void reset() {if (stack ! null) {stack.clear();}}
} 其实这个实现完全没有任何技术难度只是尽量将改功能模块化接口化方便调用。