java哈希表遍历的方法是什么

745
2023/11/22 14:45:44
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,可以使用迭代器或者增强for循环来遍历哈希表。

  1. 使用迭代器遍历哈希表:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到哈希表
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

// 获取哈希表的迭代器
Iterator<Map.Entry<String, Integer>> iterator = hashMap.entrySet().iterator();

// 使用迭代器遍历哈希表
while (iterator.hasNext()) {
    Map.Entry<String, Integer> entry = iterator.next();
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println("Key: " + key + ", Value: " + value);
}
  1. 使用增强for循环遍历哈希表:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到哈希表
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

// 使用增强for循环遍历哈希表
for (Map.Entry<String, Integer> entry : hashMap.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println("Key: " + key + ", Value: " + value);
}

无论是使用迭代器还是增强for循环,都可以遍历哈希表中的键值对,并通过getKey()getValue()方法获取键和值。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java中dateformat的作用是什么