The difference between HashMap and Hashtable

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by yanggf on 2017/12/28.
 */
public class FastFailTest {
    public static ArrayList<Integer> list = new ArrayList<>();

    public static class ThreadOne extends Thread{
        public void run() {
            Iterator<Integer> iterator = list.iterator();
            while (iterator.hasNext()){
                int i = iterator.next();
                System.out.println("ThreadOne find" + i);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static class ThreadTwo extends Thread{
        public void run() {
            int i = 0;
            while (i < 6) {
                System.out.println("ThreadTwo:" + i);
                if (i == 3) {
                    list.remove(i);
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
        }
    }

    public static Hashtable<Integer, Integer> table = new Hashtable<>();

    public static class ThreadThree extends Thread{
        @Override
        public void run(){
            Iterator iter = table.entrySet().iterator();
            while (iter.hasNext()){
                Map.Entry entry = (Map.Entry)iter.next();
                System.out.println("ThreadThree:" + entry.getKey() + "->" + entry.getValue());
            }
        }
    }

    public static class ThreadFour extends Thread{
        @Override
        public void run(){
            int i = 0;
            while (i < 6) {
                System.out.println("ThreadFour:" + i);
                if (i == 3) {
                    table.put(3, 4);
                }
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                i++;
            }
        }
    }
    public static void main(String[] args) {
//        for (int i = 0; i < 100; i++) {
//            list.add(i);
//        }
//        new ThreadOne().start();
//        new ThreadTwo().start();

        for (int i = 0; i < 100; i++) {
            table.put(i, i + 1);
        }
        new ThreadThree().start();
        new ThreadFour().start();
    }
}

1、 HashMap不支持多线程,Hashtable支持多线程   synchronized

2、HashMap的key允许null,Hashtable的key不允许null

3、HashMap的迭代器iterator是fast-fail的,Hashtable的迭代器enumerator不是fast-fail的

4、单线程环境下HashMap的速度比Hashtable速度快

5、多线程环境可以使用ConcurrentHashMap

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.