为什么 Java HashMap
中没有 map.get(index)
?
要访问 HashMap
中第一个键的值,我必须将键放入列表中,然后 list.get(0)
,然后将其传递给 map.get(list.get(0))
;我觉得这很笨拙。为什么会这样?
从 HashMap
访问“第一个或第二个元素”的正确方法是什么?
(请不要建议“将 HashMap
转换为 LinkedHashMap
并通过 迭代
访问它)。
最佳答案
要求 HashMap
的“第一个元素”没有意义,因为顺序可以(并且通常会)随着元素的添加和删除而改变。
HashMap 的文档对此进行了解释
"... makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time."
您可以通过以下实验对其进行测试:
import java.util.HashMap;
public class M {
public static void main(String[] args) {
HashMap<String, Integer> m = new HashMap<String, Integer>();
for (int i=1, p=1; i<100000; i++) {
m.put(""+i, i);
if (i == p) {
p <<= 1; // keys are reordered at power-of-two multiples
System.out.println("at " + p + ": first is now "
+ m.keySet().iterator().next());
}
}
}
}
输出是(JDK 1.7):
at 2: first is now 1
at 4: first is now 2
at 8: first is now 3
at 16: first is now 3
at 32: first is now 15
at 64: first is now 19
at 128: first is now 35
at 256: first is now 35
at 512: first is now 35
at 1024: first is now 338
at 2048: first is now 338
at 4096: first is now 1411
at 8192: first is now 3280
at 16384: first is now 6873
at 32768: first is now 10997
at 65536: first is now 10997
at 131072: first is now 10997
如果您需要可重复的排序(= 迭代元素将始终为您提供插入顺序),您始终可以使用 LinkedHashMap
。请注意,它们需要更多的内存,并且速度比标准品种稍慢。
关于java - 在java中使用索引访问 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24263779/