简体   繁体   English

LinkedHashMap遍历键

[英]LinkedHashMap iterating over the keys

我无法在文档中确认这一点,但是如果我有LinkedHashMap并在其上调用keySet()并遍历此集合,是否可以按插入顺序进行迭代?

It's specified in the Map documentation: 它在Map文档中指定:

The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. Map界面提供了三个集合视图,这些视图允许将地图的内容视为一组键,一组值或一组键-值映射。 The order of a map is defined as the order in which the iterators on the map's collection views return their elements. 映射的顺序定义为映射的集合视图上的迭代器返回其元素的顺序。 Some map implementations, like the TreeMap class, make specific guarantees as to their order; 一些地图实现(例如TreeMap类)对其顺序做出特定的保证。 others, like the HashMap class, do not. 其他的(例如HashMap类)则没有。

That means for LinkedHashMap , all the 3 methods - values() , keySet() and entrySet() , each of them providing 3 different collection views, are guaranteed to iterate in the insertion order. 这意味着对于LinkedHashMap ,保证3种方法( values()keySet()entrySet()均按插入顺序进行迭代,它们各自提供3个不同的集合视图。

Yes. 是。 See the docs(that you can not see) here: http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html 在此处查看文档(您看不到): http : //docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html

Hash table and linked list implementation of the Map interface, with predictable iteration order. Map接口的哈希表和链表实现,具有可预测的迭代顺序。 This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. 此实现与HashMap的不同之处在于,它维护贯穿其所有条目的双向链接列表。 This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). 此链表定义了迭代顺序,通常是将键插入映射的顺序(插入顺序)。 Note that insertion order is not affected if a key is re-inserted into the map. 请注意,如果将密钥重新插入到映射中,则插入顺序不会受到影响。 (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation.) (如果在调用之前m.containsKey(k)将立即返回true时调用了m.put(k,v),则将密钥k重新插入到映射m中。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM