是否有更好的方法从 ArrayList 搜索 HashMap [英] Is it there a better way to Search HashMap from ArrayList
问题描述
我正在尝试在 ListView
中实现搜索.我的 ListView
由 ArrayList
中的 HashMap
组成,我设法实现了逻辑,但我猜我的方法中有很多对象和内存分配文本更改的时间.因此,我正在寻找更少的内存分配逻辑,以便在 ArrayList
I am trying to implement Searching in ListView
. My ListView
is comprised of HashMap
in ArrayList
and I managed to implement the logic but I guess there is much object and memory allocation in my approach each time the text change. Therefore I am looking for less memory allocated logic to search in my ListView
with HashMap
in ArrayList
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//textlength = searchBar.getText().length();
//text_sort.clear();
sortedArrayList.clear();
for (int i = 0; i < myHistList.size(); i++) {
HashMap<String, String> hash = new HashMap<String, String>();
hash = myHistList.get(i);
if (hash.get("myName").toLowerCase().indexOf(searchBar.getText().toString().toLowerCase()) != -1) {
String callerNum1 = hash.get("myNumber");
String myName1 = hash.get("myName");
HashMap<String, String> searchedHash = new HashMap<String, String>();
// adding each child node to HashMap key => value
searchedHash.put("myNumber", callerNum1);
searchedHash.put("myName", myName1);
recordingFile1);
// adding HashList to ArrayList
sortedArrayList.add(searchedHash);
}
}
ListView actualLv = mPullRefreshListView.getRefreshableView();
actualLv.setAdapter(new myHistoryListAdapter(myHistory.this, sortedArrayList));
}
推荐答案
首先可以替换
HashMap<String, String> hash = new HashMap<String, String>();
hash = myHistList.get(i);
只要
HashMap<String, String> hash = myHistList.get(i);
它会稍微减少冗余对象的数量.
It will slightly reduce the number of redundant objects.
在第二步,如果您需要比较相同的字符串但忽略字母的大小写,您可以尝试简化您的 if
条件
At second step if you need to compare strings are the same but ignore letters' case you can try to simplify your if
condition
if (hash.get("myName").toLowerCase().indexOf(searchBar.getText().toString().toLowerCase()) != -1)
与
if(hash.get("myName").compareToIgnoreCase(searchBar.getText().toString()) == 0)
此外,如果您将 String callerNum1 = hash.get("myNumber");
放在 if
语句上方,那么您可以节省一些时间,因为您不需要两次查看您的 HashSet 以搜索相同的元素.它将如下所示:
Also if you put the String callerNum1 = hash.get("myNumber");
above the if
statement then you can save some time because you don't need to look through your HashSet two times to search the same element. It will look like following:
String callerNum1 = hash.get("myNumber");
if(callerNum1.compareToIgnoreCase(searchBar.getText().toString()) == 0){
...
}
这篇关于是否有更好的方法从 ArrayList 搜索 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!