简体   繁体   English

键集和值在哈希图中是否具有相同的顺序

[英]does keyset and values have same order in hashmap

as I know keyset() doesn't guarantee any particular order, however does values() get same order as keyset()? 据我所知keyset()不能保证任何特定的顺序,但是values()是否与keyset()的顺序相同? how about linkedhashmap? 链接哈希表怎么样? seems it can provide a consistent order keyset, assume that it also get a same order values()? 似乎它可以提供一致的顺序键集,假设它也获得相同的顺序values()?

哈希表中绝对没有关于顺序的承诺。

The best way to iterate through any java Map is to use the idiom: 遍历任何Java Map的最佳方法是使用以下惯用法:

for(Map.Entry<K,V> e : map.entrySet()){
  K theKey = e.getKey();
  V theValue = e.getValue();
  // do something with them!
}

This idiom makes the question irrelevant as you are going through entries in the map in the form of key, value pairs. 这个成语使问题变得无关紧要,因为您正在以键,值对的形式浏览映射中的条目。

As already noted, there is no order guarantees except for SortedMap s or LinkedHashMap and the like. 如前所述,除了SortedMapLinkedHashMap等之外,没有任何顺序保证。 If you have a total ordering on your keys, use a SortedMap : always model your problem explicitly. 如果您对键进行了总体排序,请使用SortedMap :始终明确地对问题建模。

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

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