如何在 Java HashMap 中使用 null 值作为键
是的,可以 Java HashMap 中将 null 设为键。为此,我们首先创建一个具有键值对的 HashMap -
Map<String,String>map = new HashMap<>(); map.put("Football", "A"); map.put("Squash", "B"); map.put("Cricket", "C"); map.put("Hockey", "D"); map.put("Rugby", "E");
现在,让我们将 null 值添加为键 -
map.put(null, "H");
您可以尝试获取 key 为“null”的值 -
map.get(null);
示例
import java.util.HashMap; import java.util.Map; public class Demo { public static final void main(String[] args) { Map<String,String>map = new HashMap<>(); map.put("Football", "A"); map.put("Squash", "B"); map.put("Cricket", "C"); map.put("Hockey", "D"); map.put("Rugby", "E"); map.put("Golf", "F"); map.put("Archery", "G"); System.out.println("Size of HashMap = " + map.size()); map.put(null, "H"); System.out.println("Updated Size of HashMap = " + map.size()); System.out.println("For null = " + map.get(null)); } }
输出
Size of HashMap = 7 Updated Size of HashMap = 8 For null = H
广告