探究Map中的Key和Value是否可以为空

探究Map中的Key和Value是否可以为空

因为Map是一个接口,因此要判断是否为空,要在它的具体实现类上进行具体的判断;

1.HashMap中

  • 根据如下代码测试,对于HashMap中Key和Value都可以为空
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.根据下面的测试,HashTable中Key和Value都不能为空;会出报空指针异常;

在这里插入图片描述

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));
    }

猜你喜欢

转载自blog.csdn.net/qq_45665172/article/details/113861432