Java在HashMap或HashTable中如何订购项目? [英] How does Java order items in a HashMap or a HashTable?

查看:187
本文介绍了Java在HashMap或HashTable中如何订购项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Java如何在 Map HashMap Hashtable )。密钥是由哈希码,内存引用或分配优先级排序的吗??



这是因为我在地图中注意到相同的对并不总是相同的顺序

解决方案

java.util.HashMap 是无序的;你不能也不应该承担任何事情。


这个类不能保证地图的顺序;特别是,它不能保证订单在一段时间内保持不变。


java.util.LinkedHashMap 使用插入顺序。



< blockquote>

此实现与 HashMap 不同之处在于,它维护着一个双向链接列表,通过其所有条目。此链接列表定义迭代排序,通常是将键插入到地图(插入顺序)中的顺序。


java.util.TreeMap ,a SortedMap ,使用按键的自然或自定义排序。


该图根据其键的自然顺序或比较器在地图创建时提供,具体取决于使用哪个构造函数。



I was wondering how Java orders items in the Map (HashMap or Hashtable) when they are added. Are the keys ordered by the hashcode, memory reference or by allocation precedence...?

It's because I've noticed same pairs in the Map are not always in the same order

解决方案

java.util.HashMap is unordered; you can't and shouldn't assume anything beyond that.

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

java.util.LinkedHashMap uses insertion-order.

This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order).

java.util.TreeMap, a SortedMap, uses either natural or custom ordering of the keys.

The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

这篇关于Java在HashMap或HashTable中如何订购项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆