溫馨提示×

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

小億
96
2023-12-08 14:45:44
欄目: 編程語言

在Java中,可以使用迭代器或者增強for循環(huán)來遍歷哈希表。

  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循環(huán)遍歷哈希表:
HashMap<String, Integer> hashMap = new HashMap<>();
// 添加元素到哈希表
hashMap.put("A", 1);
hashMap.put("B", 2);
hashMap.put("C", 3);

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

無論是使用迭代器還是增強for循環(huán),都可以遍歷哈希表中的鍵值對,并通過getKey()getValue()方法獲取鍵和值。

0