What are the differences between Hashmap vs Hashtable in theory?

后端 未结 4 1305
小蘑菇
小蘑菇 2020-12-20 02:53

Are there are differences between hashmap and hashtable in theory?

I don\'t mean in the concrete definitions given in Java (or the implementation), but in theory. I

4条回答
  •  [愿得一人]
    2020-12-20 02:59

    Hash Map & Hashtable

    • Both belongs to Map Interface. Keys – cannot be duplicate.
    • Hash Map  not synchronized but we can convert it to synchronizedMap. It allows maximum one null key and any number of null values.
    • Hash Table  synchronized as it is legacy class. It not allow null either in key/value.
    • The default initial capacity of Hashtable is 11, HashMap is 16.

    • Hash – will not ensure the order of insertion

    • For More information see my stack post

    public static void main(String[] args) {
        new Thread() {
            @Override public void run() {
                HashMap hm = new HashMap();
                hm.put("key0", 10); // Compiler Widens.
                hm.put("key1", null);
                hm.put("key0", new Integer(16)); // Overridden.
                hm.put(null, 20);
                hm.put(null, 70);
                hm.put(null, null);
                System.out.println("HashMap : "+hm); // hm.toString()
    
                Iterator> it = hm.entrySet().iterator();
                while (it.hasNext()) {                  
                    Map.Entry pair = (Map.Entry)it.next();
                    System.out.println(pair.getKey() + " = " + pair.getValue());
                    it.remove(); // avoids a ConcurrentModificationException
                }
                // we can conver HashMap to synchronizedMap
                Collections.synchronizedMap(hm);
    
            }
        }.start();
        new Thread() {
            @Override public void run() {
                Hashtable ht = new Hashtable();
                try {
                    ht.put("product1", 12);
                    ht.put("product2", 13);
                    ht.put("product2", 14);
                //  ht.put(null, 20);
                //  ht.put("product2", null);
                    System.out.println("hash Table : "+ht);
    
                } catch (NullPointerException nul) {
                    System.out.println("HashTable will not accept null's eighter in key/value");
                    IllegalArgumentException iae = new IllegalArgumentException("nulls not accept");
                    iae.initCause(nul);
                    throw iae;
                }               
            }
        }.start();
    }
    

提交回复
热议问题