没有合适的资源?快使用搜索试试~ 我知道了~
Java容器HashMap与HashTable详解
5星 · 超过95%的资源 1 下载量 167 浏览量
2020-08-30
20:33:07
上传
评论
收藏 64KB PDF 举报
温馨提示
试读
2页
本文主要介绍HashMap 和 Hashtable的工作原理和使用方法,有兴趣的朋友可以参考
资源推荐
资源详情
资源评论
Java容器容器HashMap与与HashTable详解详解
本文主要介绍HashMap 和 Hashtable的工作原理和使用方法,有兴趣的朋友可以参考
1、、HashMap
HashMap继承抽象类AbstractMap,实现接口Map、Cloneable, Serializable接口。HashMap是一种以键值对存储数据的容
器,
由数组+链表组成,其中key和value都可以为空,key的值唯一。HashMap是非线程安全的, 对于键值对<Key,Value>,
HashMap内部会将其封装成一个对应的Entry<Key,Value>对象。HashMap的存储空间大小是可以动态改变的:
存储过程存储过程
每个对象都有一个对应的HashCode值,根据HashCode值,调用hash函数,计算出一个hash值,根据该hash值调用indexFor函
数,计算出在table中的存储位置,如果该位置已经有值,则存储在该位置对应的桶中。
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
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++;
addEntry(hash, key, value, i);
return null;
}
public final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
public final int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue())
}
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
获取值获取值
首先根据key的HashCode码计算出hash值,然后调用indexFor函数计算该entry对象在table中的存储位置,遍历该位置对应桶
中存储的entry对象,如果存在对象的hash值和key与要查找的相同,则返回该对象。
public final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : hash(key);
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
weixin_38721119
- 粉丝: 10
- 资源: 925
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
- 1
- 2
前往页