ArrayList&l开发者_运维百科t;HashMap<String, String>>
arrayListRowsFirst = new ArrayList<HashMap<String, String>>();
Today when i was going through a code, this piece of code struck me for a while. Here are some of my questions over this declaration.
- What could be the requirement if one has to append an HashMap into an ArrayList.
- What will happen during sorting of arraylist, how it will go, will it take long time.
First off, "generic chaining" in my opinion is a poor practice. I would encourage wrapping the HashMap in a class that encapsulates the data inside, allowing the logic for manipulation to be inside the class, not just strewn about everywhere.
To answer #1, I could think of a number of scenarios. You might have languages for instance, mapping certain constants to other translations. The fact that it says rows first in the identifier makes me think perhaps it's some kind of matrix of data, and that the first String parameter will exist in all the entries of the list (a poor practice indeed.) Edit: I misunderstood your question, it appears. You would add it like any other entry. See the others' answers for example code. :-)
To answer #2, you won't be able to sort the ArrayList unless you are able to provide a comparator, at which point it's up to you how it's sorted (could be size, could be the value of a particular key, could be Math.random(), it's up to whoever writes the comparator).
There is no "special requirement" to append an HashMap to an ArrayList
.
And as neither Map
nor HashMap
implements Comparable
, so if you want to sort the ArrayList, you would have to create your own Comparator
.
A sort on a List
which contains Map
would be exactly the same as a sort on a List
wich contains anything else.
What do you mean about "append a HashMap into an ArrayList"? You add HashMaps to the ArrayList the way you add any object to a List
HashMap<String,String> hm = new HashMap<String,String>();
arrayListRowsFirst.add(hm);
You sort the array list like you sort any other - you would need to define a Comparator that compared two HashMaps, and use Collections.sort with that Comparator. How long it takes will depend a lot on how you're comparing the HashMaps.
You would add HashMaps to the ArrayList like you would any other object, using the
add()
method. Obviously it would need to be of the correct Type, in this case a HashMap of Strings.You would need to create a comparator so that your HashMaps would be sortable.
The declaration should be
List<Map<String, String>>
1 to append a map into the list, you just do
Map<String, String> map = new HashMap<String, String>();
list.add(map);
2 To sort the list, you would need a way to tell if one Map is "greater than", "less than", or "equal" to another Map. The could or might not take a long time depending on your needs. It doesn't have to take a long time.
精彩评论