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

   2025-02-13 8120
核心提示:在Java中,可以使用迭代器或者增强for循环来遍历哈希表。使用迭代器遍历哈希表:HashMapString, Integer hashMap = new HashMap(

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

使用迭代器遍历哈希表:
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);}
使用增强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()方法获取键和值。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言