Hashtable 相关的几个常规陷阱

问:下面代码段的输出结果是什么?
        Hashtable table = new Hashtable<>();
        table.put("name", "yan");
        table.put("city", "zhuhai");
        System.out.println(table.contains("name"));
        System.out.println(table.contains("yan"));
        System.out.println(table.containsKey("name"));
        System.out.println(table.containsValue("yan"));

答:输出结果为 false、true、true、true。
一定要切记 Hashtable 的 contains 方法使用的是 value 的 equals 方法,且 contains 的参数不能为 null。

问:你知道的 Hashtable 有哪些遍历方式?

答:下面给出常见的四种遍历方式。

        Hashtable table = new Hashtable();
        table.put("001", "AAA");
        table.put("002", "BBB");
        table.put("003", "CCC");
        
        //使用keys()遍历 
        Enumeration en1 = table.keys();
        while (en1.hasMoreElements()) {
            en1.nextElement();
        }
        
        //使用elements()遍历 
        Enumeration en2 = table.elements();
        while (en2.hasMoreElements()) {
            en2.nextElement();
        }
        
        //使用keySet()遍历
        Iterator it1 = table.keySet().iterator();
        while (it1.hasNext()) {
            it1.next();
        } 
        
        //使用entrySet()遍历
        Iterator> it2 = table.entrySet().iterator();
        while (it2.hasNext()) {
            it2.next();
        }

从理论上来说对于海量数据 keys() 和 elements() 方式的遍历效率会好一点,之所以 Hashtable 的迭代这么特殊是因为其后实现 Map,迭代方法主要是来自其继承的 Dictionary。

你可能感兴趣的:(Hashtable 相关的几个常规陷阱)