java - 在java中使用索引访问 map

标签 java hashmap

为什么 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/

相关文章:

java - MVC 模式的原始想法

java - 如何将 web3j 库加载到 sbt 项目?

java - 关于Java HashMap的实现

java - 使用计数器将数组插入到 HashMap 中

java hashmap键

java - 用 ASCII 替换 Unicode

java - 在 Alfresco Explorer 中将结果导出到 Excel

java - 是否可以将 Android 包导入普通的 Java 代码

java - 如何使用两个迭代器遍历 HashMap?

java - 查找桶中有多少个键