Java 中的 entrySet() 方法是什麼?
HashMap類在Java中提供了java.util.HashMap.entrySet()方法。它用於創建並返回 HashMap 中已經存在的相同元素的“集合”。它可以與循環一起使用以迭代HashMap的所有條目。方法頭
下面給出了entrySet()方法的標頭。它返回包含鍵值對的所有條目的集合視圖。要在我們的代碼中使用它,我們需要導入java.util.HashMap包。
public Set<Map.Entry<key, value>> entrySet()
參數
entrySet ()方法不接受任何參數。返回類型
java.util.HashMap.entrySet ()方法返回類集的一個實例。例子
import java.util.HashMap;
public class Driver1 {
public static void main(String[] args) {
// declare a custom hash map
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
// add data to the hash map
hashMap.put(1, "Monday");
hashMap.put(2, "Tuesday");
hashMap.put(3, "Wednesday");
hashMap.put(4, "Thursday");
hashMap.put(5, "Friday");
hashMap.put(6, "Saturday");
hashMap.put(7, "Sunday");
// print the original hash map
System.out.println("Original HashMap: " + hashMap + '\n');
// print the entrySet of the hash map
System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');
// Try adding null value in the hash map
hashMap.put(0, null);
System.out.println("hashMap.put(0, null)");
System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');
// Try adding null key and value pair to the hash map
hashMap.put(null, null);
System.out.println("hashMap.put(null, null)");
System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');
// Try adding a null character as a value in the hash map
hashMap.put(null, "\0");
System.out.println("hashMap.put(null, \"\\0\")");
System.out.println("HashMap.entrySet(): " + hashMap.entrySet() + '\n');
}
}
輸出
原始HashMap: {1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday, 6=Saturday, 7=Sunday} HashMap.entrySet(): [1=Monday, 2=Tuesday, 3=Wednesday , 4=星期四, 5=星期五, 6=星期六, 7=星期日] hashMap.put(0, null) HashMap.entrySet(): [0=null, 1=星期一, 2=星期二, 3=星期三, 4=星期四, 5=星期五, 6=星期六, 7=星期日] hashMap.put(null, null) HashMap.entrySet(): [0=null, null=null, 1=星期一, 2=星期二, 3=星期三, 4 =星期四, 5=星期五, 6=星期六, 7=星期日] hashMap.put(null, "\0") HashMap.entrySet(): [0=null, null= , 1=星期一, 2=星期二, 3=星期三,4=星期四,5=星期五,6=星期六,7=星期日]
GO TO FULL VERSION