一、Hashmap不是线程安全的,而Hashtable是线程安全的

通过查看源码可以发现,hashmap类中的方法无synchronized关键字,而hashtable类中的方法有synchronized关键字修饰。

二、Hashmap允许key和value为null,Hashtable则不允许

hashmap允许key和value为null,当key为null时会将其置于table[0]的链表中进行存储;而hashtable则会抛出异常。

 以下代码及注释来自java.util.HashTable

 public synchronized V put(K key, V value) {

     // 如果value为null,抛出NullPointerException
if (value == null) {
throw new NullPointerException();
} // 如果key为null,在调用key.hashCode()时抛出NullPointerException // ...
} 以下代码及注释来自java.util.HasMap public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
// 当key为null时,调用putForNullKey特殊处理
if (key == null)
return putForNullKey(value);
// ...
} private V putForNullKey(V value) {
// key为null时,放到table[0]也就是第0个bucket中
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}

三、索引的计算方式不同

hashmap采用“与运算”,而hashtable采用取模运算,相比较而言hashmap的计算效率更高。

/*---------hashmap---------*/
public V put(K key, V value) {
//如果table数组为空数组{},进行数组填充(为table分配实际内存空间),入参为threshold,此时threshold为initialCapacity 默认是1<<4(24=16)
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//如果key为null,存储位置为table[0]或table[0]的冲突链上
if (key == null)
return putForNullKey(value);
int hash = hash(key);//对key的hashcode进一步计算,确保散列均匀
int i = indexFor(hash, table.length);//获取在table中的实际位置
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
//如果该对应数据已存在,执行覆盖操作。用新value替换旧value,并返回旧value
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;//保证并发访问时,若HashMap内部结构发生变化,快速响应失败
addEntry(hash, key, value, i);//新增一个entry
return null;
} /*------hashtable--------------*/
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
} // Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
} addEntry(hash, key, value, index);
return null;
}

四、初始容量及扩容算法不同

hashmap的初始容量是16,而hashtable的初始容量为11;hashmap采用的算法是:2*oldSize,而hashtable采用的算法是2*oldSize+1;

以下代码及注释来自java.util.HashTable

// 哈希表默认初始大小为11
public Hashtable() {
this(11, 0.75f);
} protected void rehash() {
int oldCapacity = table.length;
Entry<K,V>[] oldMap = table; // 每次扩容为原来的2n+1
int newCapacity = (oldCapacity << 1) + 1;
// ...
} 以下代码及注释来自java.util.HashMap // 哈希表默认初始大小为2^4=16
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 void addEntry(int hash, K key, V value, int bucketIndex) {
// 每次扩充为原来的2n
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
}

the ending!

浅析Hashmap和Hashtable的更多相关文章

  1. 浅析HashMap和Hashtable的区别

    HashMap和Hashtable两个类都实现了Map接口,二者保存键值对(key-value对): HashMap和HashTable区别 第一,继承的父类不同.HashMap继承自Abstract ...

  2. Java集合专题总结(1):HashMap 和 HashTable 源码学习和面试总结

    2017年的秋招彻底结束了,感觉Java上面的最常见的集合相关的问题就是hash--系列和一些常用并发集合和队列,堆等结合算法一起考察,不完全统计,本人经历:先后百度.唯品会.58同城.新浪微博.趣分 ...

  3. java面试题——HashMap和Hashtable 的区别

    一.HashMap 和Hashtable 的区别 我们先看2个类的定义 public class Hashtable extends Dictionary implements Map, Clonea ...

  4. Map集合及与Collection的区别、HashMap和HashTable的区别、Collections、

    特点:将键映射到值的对象,一个映射不能包含重复的键,每个键最多只能映射到一个值. Map集合和Collection集合的区别 Map集合:成对出现 (情侣)                       ...

  5. HashMap和 Hashtable的比较

    Hashtable 和 HashMap的比较 1.  HashMap可以接受null(HashMap可以接受为null的键值(key)和值(value), HashTable不可以接受为null的键( ...

  6. hashMap和hashTable的区别

    每日总结,每天进步一点点 hashMap和hashTable的区别 1.父类:hashMap=>AbstractMap hashTable=>Dictionary 2.性能:hashMap ...

  7. HashMap和HashTable到底哪不同?

    HashMap和HashTable有什么不同?在面试和被面试的过程中,我问过也被问过这个问题,也见过了不少回答,今天决定写一写自己心目中的理想答案. 代码版本 JDK每一版本都在改进.本文讨论的Has ...

  8. java分享第七天-01(Hashmap和Hashtable的区别&Property)

    一.Hashmap和Hashtable的区别 1 主要:Hashtable线程安全,同步,效率相对低下 HashMap线程不安全,非同步,效率相对高 2 父类:Hashtable是Dictionary ...

  9. HashMap底层实现原理/HashMap与HashTable区别/HashMap与HashSet区别

    ①HashMap的工作原理 HashMap基于hashing原理,我们通过put()和get()方法储存和获取对象.当我们将键值对传递给put()方法时,它调用键对象的hashCode()方法来计算h ...

随机推荐

  1. 迁移python project

    1.从python官网下载同版本的安装版的python,在新机器上安装同样版本的python(python底层是用C语言写的,安装python会安装c  c++用到的库) 2.拷贝united1整个文 ...

  2. .Net dependent configuration

    error info: 解决方案:在.exe.config文件中配置Newtonsoft.Json所用版本 <runtime> <assemblyBinding xmlns=&quo ...

  3. Clover 安装 Mac 系统更新 (原版黑苹果)

    关于使用原版镜像(即 .dmg )安装黑苹果的升级,笔者写写自身经验吧. 在Clover启动的界面中与Mac OS有关的启动菜单有以下这些: Boot FileVault Prebooter from ...

  4. Lombok之使用详解

    前言 在Java中,封装是一个非常好的机制,最常见的封装莫过于get,set方法了,无论是Intellij idea 还是Eclipse,都提供了快速生成get,set方法的快捷键,使用起来很是方便, ...

  5. 算法笔记--manacher算法

    参考:https://www.cnblogs.com/grandyang/p/4475985.html#undefined 模板: ; int p[N]; string manacher(string ...

  6. linux shell 脚本 svn自动更新项目并且打包 、发布、备份

    这里先准备一个配置文件,用于保存svn地址.目的路径.用户名跟密码 配置文件名问:toolConfig.properties #svn地址 svnAddress=https://192.168.1.2 ...

  7. hbase的api操作之过滤器

    Comparison Filter:   对比过滤器:    1.RowFilter        select * from ns1:t1 where rowkey <= row100    ...

  8. Myeclipse6.5每次打开properties中文注释都会变成乱码

    发现无论怎么写properties注释,只要重新打开me就会出现乱码.默认properties是不支持中文的.所以最好用英文写properties文档.也可以写好直接翻译.已经写好的乱码直接拖到Chr ...

  9. ionic2使用cordova打包的环境搭建

    1.安装node.js(不用说了) 2.安装JDK(java的开发基础类库) 3.安装SDK(安卓开发集成包) 4.gradle( JAVA界的Weboack ,支撑app的编译,打包的流程) 5.安 ...

  10. [luogu P3960] [noip2017 d2t3] 队列

    [luogu P3960] [noip2017 d2t3] 队列 题目描述 Sylvia 是一个热爱学习的女♂孩子. 前段时间,Sylvia 参加了学校的军训.众所周知,军训的时候需要站方阵. Syl ...