查询已有链表的hashmap_hashmap-原理详解

写一点废话,工作一年,自己始终在忙碌的做业务,感觉自己没有沉淀技术积累。决定开始写技术博客,每周看一点东西,积累一点技术支持。

在一切开始之前,首先明确几个基本认知。所有的技术都是为了解决特定的问题或场景而产生的。 tell me why

对于一个新的技术,先学会如何去应用,能快速的去上手使用,在使用的时候想一想如果是你来做,你会怎么设计 how(现在欠缺的能力)

在学习的时候一定要带着问题去质疑。 what why not?

hashmap 是为了解决数据查询的问题而产生的,能够以o(1)的查询效率做查询。(查询什么样的数据)

hashmap的核心思想是维护一个函数 f(key)=index。对于任意的key,通过一次映射能够快速定位到他所在的地址,获取该地址下存储对value,高效查询。

f()是什么?该怎么维护?

f()是什么?每一次查询hashmap做了什么?

从结构实现来讲,HashMap是数组+链表+红黑树(JDK1.8增加了红黑树部分)实现的,如下如所示。(数据+链表 为什么是数组+链表?这种存储的优点是什么?链表+链表可以吗LinkHashMap,有什么优点)

//整个hashmap就是一个 Node[] table,即哈希桶数组,数组存储的是这些节点static class Node implements Map.Entry {

final int hash;

final K key;

V value;

Node next;

Node(int hash, K key, V value, Node next) {

this.hash = hash;

this.key = key;

this.value = value;

this.next = next;

}

public final K getKey() { return key; }

public final V getValue() { return value; }

public final String toString() { return key + "=" + value; }

public final int hashCode() {

}

public final V setValue(V newValue) {

}

public final boolean equals(Object o) {

}

我们模拟一个场景,用一个hashmap来存储城市-城市简称这个健值对,每个人都有其对应的年龄属性。现在我们要查询北京的简称map.get("北京")。hashMap get()流程图

问题:

1.(h = key.hashCode())^(h >>>16) 高位与低位异或做了什么事情?

将679541转化为2进制 0000 0000 0000 1010 0101 1110 0111 0101

h>>>16 0000 0000 0000 0000 0000 0000 0000 1010

结果 0000 0000 0000 1010 0101 1110 1111 1111

由上可知对679541进行取模计算,假如数组的长度为16,那么只有后面4位数会对取模结果有影响,而hash散列表的核心思想是要使散列的数据更加均匀,让数据的高位和低位进行异或可以使得影响hash结果的位数更多。

2.(n -1)& hash为什么能代替模运算,优化在哪里?

首先这样做的一个前提是n为2的整数次幂,比如n为32

31 0000 0000 0000 0000 0000 0000 0001 1111

结果 0000 0000 0000 1010 0101 1110 1111 1111

对31和hash的结果进行与操作,n-1是由0和1分隔开,两个都相同的才为1,相当于取模运算

3.为什么要重写equals和hashCode函数?

对于自定义对象,如果不重写hashCode,那么hashCode默认是对地址做hashCode而不是对内容做hashCode,两个对象

4.为什么要采用链表+红黑树这种组合,优化在哪里?

首先说一下链表的缺点,对于每一个table查询的效率都是o(1),但是如果hash函数设计的不好,导致一个table里面长链的数量过多,极端情况下查询效率就会是o(n)

为什么采用红黑树,红黑树自平衡,稳定,最坏情况下也是log(n)。非平衡二叉树,极端情况下等于单链表。

为什么采用链表+红黑树,在长链的情况下效率会很低效,短链的情况下维护红黑树的代价就会比查询的代价高了

//hashMap中的hash函数//为什么要高位和低位异或 当数组长度较小时,高位数据都是无效的,对计算结果不起作用static final int hash(Object key) {

int h;

return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);

}

//String的hashCode方法 可以思考一下为什么是31public int hashCode() {

int h = hash;

if (h == 0 && value.length > 0) {

char val[] = value;

for (int i = 0; i < value.length; i++) {

h = 31 * h + val[i];

}

hash = h;

}

return h;

}

//hashmap的get函数public V get(Object key) {

Node e;

return (e = getNode(hash(key), key)) == null ? null : e.value;

}

final Node getNode(int hash, Object key) {

Node[] tab; Node first, e; int n; K k;

//tab[(n - 1) & hash 散列表取余数 保证数组的长度为2的幂次方时n-1前面的都可以舍弃 if ((tab = table) != null && (n = tab.length) > 0 &&

(first = tab[(n - 1) & hash]) != null) {

if (first.hash == hash && // always check first node 重写equals函数

((k = first.key) == key || (key != null && key.equals(k))))

return first;

if ((e = first.next) != null) {

if (first instanceof TreeNode)

//判断是否是红黑树,如果是的话查找红黑树 return ((TreeNode)first).getTreeNode(hash, key);

do {

if (e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k))))

return e;

} while ((e = e.next) != null);

}

}

return null;

}

上面讲的是查询,接下来我们看一看怎么去维护一个hashMap。

hashmap的初始化 首先看下hashmap的几种构造方式

//initialCapacity初始化数据容量默认16 loadFactor 负载因子 默认0.75 为什么是0.75public HashMap(int initialCapacity, float loadFactor) {

if (initialCapacity < 0)

throw new IllegalArgumentException("Illegal initial capacity: " +

initialCapacity);

if (initialCapacity > MAXIMUM_CAPACITY)

initialCapacity = MAXIMUM_CAPACITY;

if (loadFactor <= 0 || Float.isNaN(loadFactor))

throw new IllegalArgumentException("Illegal load factor: " +

loadFactor);

this.loadFactor = loadFactor;

this.threshold = tableSizeFor(initialCapacity);

}

public HashMap(int initialCapacity) {

this(initialCapacity, DEFAULT_LOAD_FACTOR);

}

public HashMap() {

this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted }

//将一个map直接构造为hashmap,初始容量为map.size()/loadFactor+1。再tableSizeForpublic HashMap(Map extends K, ? extends V> m) {

this.loadFactor = DEFAULT_LOAD_FACTOR;

putMapEntries(m, false);

}

//核心逻辑 将容量大小变为最接近的二次幂的值 怎么做到的?//假设cap为20 天才!!static final int tableSizeFor(int cap) {

int n = cap - 1; n=19 // 0000 0000 0000 0000 0000 0000 0001 0011 n |= n >>> 1; //n>>>1 0000 0000 0000 0000 0000 0000 0000 1001 //n |= n >>> 1 0000 0000 0000 0000 0000 0000 0001 1011 n |= n >>> 2; //n>>>2 0000 0000 0000 0000 0000 0000 0000 0110 //n |= n >>> 2 0000 0000 0000 0000 0000 0000 0001 1111 n |= n >>> 4;

n |= n >>> 8;

n |= n >>> 16;

return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;

}

接下来看put的核心方法

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,

boolean evict) {

Node[] tab; Node p; int n, i;

//hashMap的初始化是在第一次调用put方法时进行的 if ((tab = table) == null || (n = tab.length) == 0)

n = (tab = resize()).length;

//如果table为空,直接插入 if ((p = tab[i = (n - 1) & hash]) == null)

tab[i] = newNode(hash, key, value, null);

else {//存在hash Node e; K k;

if (p.hash == hash &&

((k = p.key) == key || (key != null && key.equals(k))))

e = p;

//判断table[i = (n - 1) & hash]是否为红黑树 else if (p instanceof TreeNode)

//万恶之源,红黑树,下周末研究 e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);

else {

for (int binCount = 0; ; ++binCount) {

if ((e = p.next) == null) {

p.next = newNode(hash, key, value, null);

if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st//当数组长度大于64,链表长度超过8的时候会转化为红黑树,数组长度小于64会先扩容resize() treeifyBin(tab, hash);

break;

}

if (e.hash == hash &&

((k = e.key) == key || (key != null && key.equals(k))))

break;

p = e;

}

}

//如果存在,则更新。 if (e != null) { // existing mapping for key V oldValue = e.value;

if (!onlyIfAbsent || oldValue == null)

e.value = value;

afterNodeAccess(e);//为了linkHashMap留的 return oldValue;

}

}

++modCount;

//如果hashmap的size大于阈值,扩容 if (++size > threshold)

resize();

afterNodeInsertion(evict);//LinkHashMap留的 return null;

}

//红黑树变成链表 链表转红黑树 有时间再研究,重点是平衡红黑树

resize扩容:

final Node[] resize() {

Node[] oldTab = table;

int oldCap = (oldTab == null) ? 0 : oldTab.length;

int oldThr = threshold;

int newCap, newThr = 0;

if (oldCap > 0) {

if (oldCap >= MAXIMUM_CAPACITY) {

threshold = Integer.MAX_VALUE;

return oldTab;

}

else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&

oldCap >= DEFAULT_INITIAL_CAPACITY)

newThr = oldThr << 1; // double threshold }

else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr;

else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY;

newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);

}

if (newThr == 0) {

float ft = (float)newCap * loadFactor;

newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?

(int)ft : Integer.MAX_VALUE);

}

threshold = newThr;

@SuppressWarnings({"rawtypes","unchecked"})

Node[] newTab = (Node[])new Node[newCap];

table = newTab;

if (oldTab != null) {

//遍历oldTab,对每一个节点或者链表,尾插法遍历,头插法在高并发中会出现环 for (int j = 0; j < oldCap; ++j) {

Node e;

if ((e = oldTab[j]) != null) {

oldTab[j] = null;

if (e.next == null)

newTab[e.hash & (newCap - 1)] = e;

else if (e instanceof TreeNode)

//看完红黑树再研究 ((TreeNode)e).split(this, newTab, j, oldCap);

else { // preserve order //这段代码写的很好,扩容之后,之前的链表上的节点,有两种可能 //1.放在之前的位置上2.放在j+oldCap上,把一个链表拆分为两个链表 Node loHead = null, loTail = null;

Node hiHead = null, hiTail = null;

Node next;

do {

next = e.next;

if ((e.hash & oldCap) == 0) {

if (loTail == null)

loHead = e;

else

loTail.next = e;

loTail = e;

}

else {

if (hiTail == null)

hiHead = e;

else

hiTail.next = e;

hiTail = e;

}

} while ((e = next) != null);

if (loTail != null) {

loTail.next = null;

newTab[j] = loHead;

}

if (hiTail != null) {

hiTail.next = null;

newTab[j + oldCap] = hiHead;

}

}

}

}

}

return newTab;

}

遍历

public class HashMapTraverse {

public static void main(String[] args) {

Map map = new HashMap();

map.put("1", "value1");

map.put("2", "value2");

map.put("3", "value3");

map.put("4", "value4");

// 第一种:普通使用,二次取值

System.out.println("通过Map.keySet遍历key和value:");

for (String key : map.keySet()) {

System.out.println("KEY:" + key + " " + "VALUE:" + map.get(key));

}

System.out.println("\n通过Map.entrySet使用iterator遍历key和value: ");

Iterator map1it = map.entrySet().iterator();

while (map1it.hasNext()) {

Map.Entry entry = (Entry) map1it.next();

System.out.println("Key: " + entry.getKey() + " Value: " + entry.getValue());

}

// 第三种:推荐,尤其是容量大时

System.out.println("\n通过Map.entrySet遍历key和value");

for (Map.Entry entry : map.entrySet()) {

System.out.println("KEY:" + entry.getKey() + " " + "VALUE:" + entry.getValue());

}

// 第四种

System.out.println("\n通过Map.values()遍历所有的value,但不能遍历key");

for (String v : map.values()) {

System.out.println("The value is " + v);

}

// 第五种 通过JDK1.8的新特性Lambda表达式来遍历

map.forEach((key,value) -> {

System.out.println(key + "===="+ value);

});

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Value* ApplyOneValue(int flag = 1)//flag:0代表在hashmap外部申请,1代表在hashmap内部申请 { Value *vl = NULL; if (node_list_head_) { if (value_status_.free_num_ > 1) { ValueNode* tmp = node_list_head_ ; node_list_head_ = node_list_head_->next_node_; tmp->next_node_ = NULL; value_status_.free_num_--; tmp->value_.use_count_ = flag; vl = &(tmp->value_); //return &(tmp->value_); } else { ValueNode* tmp_node = new ValueNode[kDefaultAddSize]; ValueNode* cur_node = tmp_node; if (!tmp_node) { return NULL; } vec_memptr_.push_back(tmp_node); for (uint32_t i = 1; i< kDefaultAddSize; i++) { cur_node->value_.node_ptr_ = (void*)cur_node; cur_node->next_node_ = tmp_node + i; cur_node = cur_node->next_node_; } value_status_.free_num_ += kDefaultAddSize; value_status_.total_size_ += kDefaultAddSize; node_list_head_->next_node_ = tmp_node; node_list_tail_ = cur_node; node_list_tail_->next_node_ = NULL; node_list_tail_->value_.node_ptr_ = (void*)node_list_tail_; ValueNode* tmp = node_list_head_ ; node_list_head_ = node_list_head_->next_node_; tmp->next_node_ = NULL; value_status_.free_num_--; tmp->value_.use_count_ = flag; vl = &(tmp->value_); //return &(tmp->value_); } } if(NULL != vl) { //reverse start; if(rphead && ::is_open_reverse) { rphead->CdrRaw.ncdrid = cdrgetid(rphead->lcoreid); //创建父cdrid; rphead->CdrRaw.tstart.tm_cycles = rphead->tstart.tm_cycles; rphead->CdrRaw.cdrstat = PACKET_BEGIN; rphead->btCurStaus = PACKET_BEGIN; pubSendPkt((void*)rphead); //存储父cdr信息; vl->SetReverse(rphead->CdrRaw.ncdrid, rphead->CdrRaw.tstart.tm_cycles); } //返回; return vl; } return NULL; }代码意思
最新发布
06-08

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值