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