我看到了涉及该主题的答案,但想知道是否有人有任何示例,其中您从 HashMap 派生的键集和值列表将具有不同顺序的键和值。我了解条目本身在 HashMap 中可能具有未定义的顺序,但键和值的列表是否可以相互乱序?
这里有一段简短的说明:
public class App {
public static void main(String[] args) {
Map<String,String> stateCapitols = new HashMap<>();
stateCapitols.put("AL", "Montgomery");
stateCapitols.put("AK", "Juneau");
stateCapitols.put("CO", "Denver");
stateCapitols.put("FL", "Tallahassee");
stateCapitols.put("Indiana", "Indianapolis");
stateCapitols.keySet().stream().forEach(System.out::println);
System.out.println();
stateCapitols.values().stream().forEach(System.out::println);
}
}
在上面的示例中,AL
是否会出现在与 Denver
(或任何其他值)相同的位置?
最佳答案
让我们再次看一下关于 Map
中迭代顺序的 Java SE API 语言契约(Contract):
Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.
和HashMap
:
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.
由于明确指出 HashMap 迭代器没有顺序,因此不能假设即使在调用 same 方法之间迭代也会稳定,更不用说在调用 不同的方法keySet()
和values()
。
有用的是,Map
有一个方法 entrySet()
这正是您所需要的:它以配对键和值的方式遍历映射内容。任何时候您都需要依赖这对的两个部分时,都可以使用这种方法。
随着 Java 许可变更的生效,那些认为他们可能会一直使用 Oracle 的 Java 实现的个人和组织现在正在寻找替代实现。依赖单一实现的未成文细节是极其危险的,现在比 Oracle 许可和定价变化之前更是如此。
关于java - 独立迭代时,无序 HashMap 中的键和值是否对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54738638/