共計 808 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 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()
方法獲取鍵和值。
丸趣 TV 網 – 提供最優質的資源集合!
正文完