简体   繁体   English

使用Map接口而不是List接口的实现在BaseAdapter中存储数据

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

I want to use one of the implementations of the Map interface instead of implementing the ArrayList to store data in BaseAdapter. 我想使用Map接口的一种实现方式,而不是实现ArrayList在BaseAdapter中存储数据。 I'm looking for the best way to get values from Map by index. 我正在寻找按索引从Map中获取值的最佳方法。 Creating lists from map when i have index seem to be highly not efficient. 当我有索引时从地图创建列表似乎效率不高。

@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);
}

Any suggestion how to do it in right way? 任何建议如何以正确的方式做到这一点?

Thanks in advanace. 谢谢。

For performance, you need to keep ArrayList with values of your Map in your adapter separately : 为了提高性能,您需要在适配器中单独保留ArrayListMap值:

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

You will also need to update the list every time your map changes and you are about to call notifyDataSetChanged() 每当地图更改并且您将要调用notifyDataSetChanged()时,您还需要更新列表。

This way, you get optimal O(1) performance (as it should be) for your getItem() : 这样,您将为getItem()获得最佳的O(1)性能(应该如此):

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

and don't forget to return correct value in getCount() : 并且不要忘记在getCount()中返回正确的值:

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

Note, there will be no guarantee on how values of your list (coming from the map) will be ordered, so you may want to sort them as well. 请注意,无法保证列表值(来自地图)的排序方式,因此您可能也希望对其进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM