在Java中,可以使用迭代器或者增强for循环来遍历哈希表。
- 使用迭代器遍历哈希表:
HashMaphashMap = new HashMap<>(); // 添加元素到哈希表 hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put("C", 3); // 获取哈希表的迭代器 Iterator > iterator = hashMap.entrySet().iterator(); // 使用迭代器遍历哈希表 while (iterator.hasNext()) { Map.Entry entry = iterator.next(); String key = entry.getKey(); Integer value = https://www.yisu.com/ask/entry.getValue();"Key: " + key + ", Value: " + value); }
- 使用增强for循环遍历哈希表:
HashMaphashMap = new HashMap<>(); // 添加元素到哈希表 hashMap.put("A", 1); hashMap.put("B", 2); hashMap.put("C", 3); // 使用增强for循环遍历哈希表 for (Map.Entry entry : hashMap.entrySet()) { String key = entry.getKey(); Integer value = https://www.yisu.com/ask/entry.getValue();"Key: " + key + ", Value: " + value); }
无论是使用迭代器还是增强for循环,都可以遍历哈希表中的键值对,并通过getKey()
和getValue()
方法获取键和值。