参考网址:Java注解 -Java教程™
HashMap与HashTable以及ConcurrentHashMap的区别:
HashMap Hashtable区别_shohokuf的专栏-优快云博客
HashTable的键与值都不能为空,HashMap的键与值都可以为空。
HashTable与值相关的方法(get,put等)都在方法前添加了synchronized关键字,因此HashTable是线程安全的,HashMap则没有增加该关键字,是线程不安全的。
HashTable复写了hashcode与equals方法,hashcode为每个条目的hashcode之和,equals重写,结果是HashMap只要键值对与HashTable相同,HashTable可以通过equalsHashMap返回true。HashMap没有重写hashcode与equals方法。
由于HashTable是线程安全的,HashMap是线程不安全的,所以当多个线程同时向其中添加数据时,HashMap可能会出现数据的丢失现象,HashTable却不会。
public class AboutMap {
static Map<String, Integer> map = new HashMap<>();
static Map<String, Integer> table = new Hashtable<>();
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()-> {
for (int i = 0; i < 100; i++) {
map.put("a"+i, i);
table.put("a"+i, i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread1");
Thread thread2 = new Thread(()-> {
for (int i = 0; i < 100; i++) {
map.put("b"+i, i);
table.put("b"+i, i);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"thread2");
thread.start();
thread2.start();
while (thread.isAlive()||thread2.isAlive()) {
Thread.sleep(5);
}
System.out.println("map size is "+map.size()+", table size is "+table.size());
}
}
结果为:map size is 175, table size is 200