HashMap原理及put与get方法调用过程

HashMap的原理

HashMap的数据结构为数组+链表,以key,value的形式存储,通过调用put和get方法来存制和取值。

        它内部维护了一个entry数组。得到key的hashcode值将其移位按位与运算,然后在通过跟数组的长度-1做逻辑与运算得到一个index值来确定数据存储在entry数组当中的位置,通过链表来解决hash冲突问题。当发生碰撞了,对象将会存储在链表的下一个节点中。

è¿éåå¾çæè¿°

get方法调用

1、当调用get方法时会调用hash函数,这个hash函数会将key的hashCode值返回,返回的hashcode与entry数组长度-1进行逻辑与运算得到一个index值,用这个index值来确定数据存储在entry数组当中的位置。

2、通过循环来遍历索引位置对应的链表,初始值为数据存储在entry数组当中的位置,循环条件为entry对象不为null,改变循环条件为entry对象的下一个节点。

3、如果hash函数得到的hash值与entry对象中key的hash值相等并且entry对象当中的key值与get方法传进来的key值equals相同则返回entry对象的value值,否则返回null。

è¿éåå¾çæè¿°

put方法调用

1、调用hash函数得到key的hashcode值

2、通过hashcode值与数组长度-1逻辑与运算得到一个index值

3、遍历索引位置对应的链表,如果entry对象的hash值与hash函数得到的hash值相等并且该entry对象的key值与put方法传过来的key值相等则将该entry对象的value值付给一个变量,并将该entry对象的value值重新设置为put方法传过来的value值。将旧的value返回。

4、添加entry对象到相应的索引位置

è¿éåå¾çæè¿°

posted @ 2019-03-19 17:46  strawqqhat  阅读(1027)  评论(0编辑  收藏  举报
#home h1{ font-size:45px; } body{ background-image: url("放你的背景图链接"); background-position: initial; background-size: cover; background-repeat: no-repeat; background-attachment: fixed; background-origin: initial; background-clip: initial; height:100%; width:100%; } #home{ opacity:0.7; } .wall{ position: fixed; top: 0; left: 0; bottom: 0; right: 0; } div#midground{ background: url("https://i.postimg.cc/PP5GtGtM/midground.png"); z-index: -1; -webkit-animation: cc 200s linear infinite; -moz-animation: cc 200s linear infinite; -o-animation: cc 200s linear infinite; animation: cc 200s linear infinite; } div#foreground{ background: url("https://i.postimg.cc/z3jZZD1B/foreground.png"); z-index: -2; -webkit-animation: cc 253s linear infinite; -o-animation: cc 253s linear infinite; -moz-animation: cc 253s linear infinite; animation: cc 253s linear infinite; } div#top{ background: url("https://i.postimg.cc/PP5GtGtM/midground.png"); z-index: -4; -webkit-animation: da 200s linear infinite; -o-animation: da 200s linear infinite; animation: da 200s linear infinite; } @-webkit-keyframes cc { from{ background-position: 0 0; transform: translateY(10px); } to{ background-position: 600% 0; } } @-o-keyframes cc { from{ background-position: 0 0; transform: translateY(10px); } to{ background-position: 600% 0; } } @-moz-keyframes cc { from{ background-position: 0 0; transform: translateY(10px); } to{ background-position: 600% 0; } } @keyframes cc { 0%{ background-position: 0 0; } 100%{ background-position: 600% 0; } } @keyframes da { 0%{ background-position: 0 0; } 100%{ background-position: 0 600%; } } @-webkit-keyframes da { 0%{ background-position: 0 0; } 100%{ background-position: 0 600%; } } @-moz-keyframes da { 0%{ background-position: 0 0; } 100%{ background-position: 0 600%; } } @-ms-keyframes da { 0%{ background-position: 0 0; } 100%{ background-position: 0 600%; } }