开发者

Android: Map of ArrayList's

I use a custom list adapter and ArrayList for my ListView. This 开发者_开发技巧solution was good enough but now I need to use Map of ArrayLists, something like this:

TreeMap<String, ArrayList<ItemsModel>>

where ItemsModel is a Java bean. Earlier I used to populate this ArrayList it that way:

itemsDataArrayList.add(itemModel)

Now I faced some difficulties with Map interface. First, I don't know how to populate my new Map structure: I suppose this

mapInstance.put(itemModel.getItemName.toString(), itemsDataArrayList)

won't work because itemsDataArrayList is the list of elements, not a certain element.

Second, I'm not sure how to properly declare this map instance in my ItemsAdapter class. When I was using just ArrayList it was very simple. Some examples would be very helpful.


What I recommend you look into / try is creating your own BaseAdapter. When you override this class it will give you all the functions you need to override to populate the list view.

This has the advantage of giving you complete control of what is put into the listview and how each view is created.

Then after you get it working I recommend looking into the ViewHolder design pattern along with recycling views which is a great way of improving efficiency when scrolling the listview.


What you are really looking for seem to be a MultiMap. To your first Question - your attemp was quite good, you can only put ArrayLists as values into your TreeMap.

The Problem with this might be, that if you want to add some ItemsModel to your Map, you first need to get the List of the key, and then add the ItemsModel to that list. Additionally you need to ensure, that this list for this particular key exist, and if not, create it.

Example:

String key = "hi";
ArrayList keyList = mapInstance.get(key);
if (keyList == null) {
   keyList = new ArrayList();
   mapInstance.put(key, keyList);
}
keyList.add(itemsModelInstance);

A get()/contains() and so on may be somehow equal. I'd suggest you build your own Multimap<?,?> Implementation or just take an existing one, like the one from Guava (link above).

Kind regards,

avi

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜