gpt4 book ai didi

java - 访问 HashMap 的元素

转载 作者:行者123 更新时间:2023-12-02 07:14:05 26 4
gpt4 key购买 nike

我可以分别访问HashMap的第一个和第二个元素吗?我的意思是如果我有一个 HashMap

Map<Integer, Integer> testMap = new HashMap<Integer, Integer>();
int f = testMap.first();

我知道没有这样的功能,但是我如何访问该元素?

最佳答案

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.

Reference

您可以使用维护插入顺序的LinkedHashMapTreeMap

LinkedHashMap

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

TreeMap

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

关于java - 访问 HashMap 的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15171840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com