Explore whether the Key and Value in the Map can be empty

Explore whether the Key and Value in the Map can be empty

Because Map is an interface, it is necessary to judge whether it is empty or not, and make specific judgments on its concrete implementation class;

1.HashMap中

  • According to the following code test, both Key and Value in HashMap can be empty ;
public static void main(String[] args) {
    
    
        Map<Object,Object> map = new HashMap<>();
        map.put(null,null);
        String str = (String)map.get(null);
        System.out.println(str);
        map.put(null,3);
        System.out.println(map.get(null));
        map.put("好",null);
        System.out.println(map.get("好"));
    }

2.HashTable中

1. According to the following test, neither Key nor Value in HashTable can be empty ; a null pointer exception will be reported;

Insert picture description here

public static void main(String[] args) {
    
    
        Map<Object,Object> map = new Hashtable<>();
       /*map.put(null,null);
        System.out.println(map.get(null));*/
        /*map.put(null,3);
        System.out.println(map.get(null));*/
        map.put(3,null);
        System.out.println(map.get(3));
    }

Guess you like

Origin blog.csdn.net/qq_45665172/article/details/113861432