Reputation: 3975
I need to use Maps in Java for an Android Application. But the problem is that the list gets sorted automatically. How do I use Maps to get the data in the same order as I have inserted data.
Upvotes: 15
Views: 8036
Reputation: 8101
You should use LinkedHashMap
for this purpose..Visit Android Docs and Java Docs for more details.
Upvotes: 27
Reputation: 21684
As you and I have discovered, LinkedHashMap isn't very helpful. (What is the point of its existence, anyway?)
I have a hashlist (semantically, I think it should have been called hashedlist)
It has an arraylist and a hashmap. The arraylist stores the key.
A hashlist.put(key, value) would perform
A hashlist.get(int position) would perform - a map.get(list.get(position))
This is a simplification of HashVector and HashTree classes I wrote back in 2003 when I needed to model javascript and xml objects in Java, retaining their order. However, I did not find the time or necessity to simplify the hashtree for gwt serializability.
On second thoughts, how does GWT implement a hashmap? I think when I have the time, I need to replace the hashmap with faststringmap. Google's faststringmap is not public. It is for GWT compiler private use. So you have to copy its code and change it into a public class: http://code.google.com/p/google-web-toolkit/source/browse/trunk/user/src/com/google/gwt/user/client/ui/FastStringMap.java
May be, GWT compiler would have silently used it anyway - should I bother to micromanage the compiler replace hashmap with faststringmap?
BTW,
You could still look for the hashtree by googling "googlecode synthful hashtree".
The Hashtree allows you to create a tree of objects and allows you to retrieve your objects using the an dot-convention xpath like path.
hashtree.get("hello.dolly.how.are.you");
The separator could be respecified so that you could store or get using
hashtree.get("hello/dolly/how/are/you");
hashtree.put("hello/dolly/how/are/you", value);
Upvotes: 2
Reputation: 14051
A LinkedHashMap will keep the data in the same order as it has been inserted.
Upvotes: 2