简体   繁体   中英

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()? how about linkedhashmap? seems it can provide a consistent order keyset, assume that it also get a same order values()?

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

The best way to iterate through any java Map is to use the idiom:

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. If you have a total ordering on your keys, use a SortedMap : always model your problem explicitly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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