ohana
ohana

Reputation: 285

what data structure in java suppport sort/order

i use a hashmap to store some data, but i need to keep it in ascending order whenever new data saved to the hashmap or old data move out of the hashmap. but hashmap itself doesn't suppport order, what data structure i can use to support order? Thanks

Upvotes: 0

Views: 3058

Answers (2)

Freddie
Freddie

Reputation: 1707

LinkedHashMap may be what you're looking for. http://download.oracle.com/javase/1.4.2/docs/api/java/util/LinkedHashMap.html

Upvotes: 2

Andrzej Doyle
Andrzej Doyle

Reputation: 103787

TreeMap would be the canonical sorted map implementation. Note that this is sorted on the keys, which I presume is what you're after, but if not it won't be suitable.

Since Java 6 also comes with a SortedMap interface, you can look at the list of classes which implement it (on the linked Javadoc page), and choose between those. Implementing this method only guarantees that they have some sort of defined iteration order, you'd have to read the descriptions of each class to see if it's what you like.

TreeMap isn't a hashmap, in that it isn't backed by a hashtable to provide amortised O(1) inserts. However, it's not possible to maintain a sorted map with O(1) inserts anyway (since you have to inspect at least some of the existing elements to work out where the new element should go), and hence the O(lg n) performance of TreeMap is as good as you'll get in this case.

Upvotes: 8

Related Questions