是否有更好的方法从ArrayList搜索HashMap

时间:2013-11-13 10:54:54

标签: android listview android-listview arraylist android-arrayadapter

我正在尝试在ListView中实施搜索。我的ListViewHashMap中的ArrayList组成,我设法实现逻辑,但我想每次文本更改时我的方法中都有很多对象和内存分配。因此,我正在寻找更少的内存分配逻辑来搜索ListView HashMap 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)); }

{{1}}

1 个答案:

答案 0 :(得分:0)

首先你可以替换

HashMap<String, String> hash = new HashMap<String, String>(); 
hash = myHistList.get(i);

只是

 HashMap<String, String> hash = myHistList.get(i);

它会略微减少冗余对象的数量。

第二步,如果您需要比较字符串是相同但忽略字母的情况,您可以尝试简化if条件

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来搜索相同的元素。它将如下所示:

String callerNum1 = hash.get("myNumber");

if(callerNum1.compareToIgnoreCase(searchBar.getText().toString()) == 0){
     ...
}