Java 如何对 HashMap 或 HashTable 中的项目进行排序? [英] How does Java order items in a HashMap or a HashTable?

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

问题描述

我想知道在添加Map(HashMapHashtable)中的项目时,Java 如何对其进行排序.键是按哈希码、内存引用还是按分配优先级排序的...?

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...?

这是因为我注意到 Map 中的相同对并不总是以相同的顺序

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

推荐答案

java.util.HashMap 是无序的;除此之外,你不能也不应该假设任何事情.

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 使用插入顺序.

java.util.LinkedHashMap uses insertion-order.

这个实现与 HashMap 的不同之处在于它维护一个双向链表,贯穿其所有条目.这个链表定义了迭代顺序,这通常是键被插入到映射中的顺序(插入顺序).

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.TreeMapSortedMap,使用键的自然或自定义排序.

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

地图根据其键的自然顺序进行排序,或者根据地图创建时提供的 Comparator 进行排序,具体取决于使用的构造函数.

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天全站免登陆