美文网首页
HashMap和Hashtable

HashMap和Hashtable

作者: 荒天帝886 | 来源:发表于2019-08-01 15:06 被阅读0次

    https://www.cnblogs.com/williamjie/p/9099141.html

    HashMap的key和value都可以为null

    Hashtable的key和value都不能为null

        @Test
        public void test1() {
            Map<Object, Object> map = new HashMap<>();
            map.put("a", "aaa");
            map.put("b", "bbb");
            map.put("c", "ccc");
            map.put("d", null);
            map.put(null, "eee");
            System.out.println(map.get("d")); //null 值为null
            System.out.println(map.get("e")); //null 没有key
            System.out.println(map.get(null)); //null 没有key
            System.out.println(map.containsKey(null));
        }
    
        @Test
        public void test2() {
            Hashtable<Object, Object> table = new Hashtable<>();
            table.put("a", "aaa");
            table.put("b", "bbb");
            table.put("c", "ccc");
    //        table.put("d", null);       //NullPointerException
    //        table.put(null, "eee");     //NullPointerException
            System.out.println(table.get("a")); //null 值为null
            System.out.println(table.get("b")); //null 没有key
            System.out.println(table.contains("aaa"));
            System.out.println(table.containsValue("aaa"));
        }
    

    相关文章

      网友评论

          本文标题:HashMap和Hashtable

          本文链接:https://www.haomeiwen.com/subject/yboqdctx.html