簡體   English   中英

使用Map接口而不是List接口的實現在BaseAdapter中存儲數據

[英]Using implementation of Map interface instead of List interface to store data in BaseAdapter

我想使用Map接口的一種實現方式,而不是實現ArrayList在BaseAdapter中存儲數據。 我正在尋找按索引從Map中獲取值的最佳方法。 當我有索引時從地圖創建列表似乎效率不高。

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
List<Map.Entry<String, String>> 
list = new LinkedList<Map.Entry<String,String>>(this.countries.entrySet());
return list.get(position);
}

任何建議如何以正確的方式做到這一點?

謝謝。

為了提高性能,您需要在適配器中單獨保留ArrayListMap值:

// Map<String, String> countries;
ArrayList<String> countryList = new ArrayList<String>(countries.values());

每當地圖更改並且您將要調用notifyDataSetChanged()時,您還需要更新列表。

這樣,您將為getItem()獲得最佳的O(1)性能(應該如此):

@Override
public Object getItem(int position) {
    return position < countryList.size() ? countryList(position) : null;
}

並且不要忘記在getCount()中返回正確的值:

@Override
public Object getCount() {
    return countryList.size();
}

請注意,無法保證列表值(來自地圖)的排序方式,因此您可能也希望對其進行排序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM