开发者

what data structure in java suppport sort/order

开发者 https://www.devze.com 2023-02-14 11:40 出处:网络
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 mo开发者_运维知识库ve out of the hashmap. but hashmap itself doesn\'t su

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 mo开发者_运维知识库ve out of the hashmap. but hashmap itself doesn't suppport order, what data structure i can use to support order? Thanks


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.


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

0

精彩评论

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

关注公众号