是的,您可以在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");
现在,让我们添加空值作为键-
map.put(null, "H");
您可以尝试将键的值获取为“ 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