本文是对高淇版Java三百集,HashMap内容学习的记录。Map接口实现类有HashMap,TreeMap,HashTable和Properties等。
HashMap的本质采用了Hash表,这是一种非常重要的数据结构,源码中表示为transient Node<K,V>[] table
,成为"位桶数组"。其基本原理用一句话来形容就是:在数组中存放单链表。,jdk8以后当单链表长度大于8情况下,采用红黑树。
一、Map常用方法
1.1 put()方法
public V put(K key, V value)
1.2 get()方法
public V get(Object key)
1.3 remove()方法
public V remove(Object key)
1.4 keySet()方法
public Set<K> keySet()
二、自定义实现HashMap功能
(1) MyHashNode类
package cn.edu.ucas.gqlearn;
/**
* @Author: hyk
* @Date: 2020/7/22
* @version: 1.0
*/
public class MyHashNode<K,V> {
int hash;
K key;
V value;
MyHashNode<K,V> next;
public MyHashNode() {
}
public MyHashNode(int hash,K key, V value, MyHashNode<K, V> next) {
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}
@Override
public String toString() {
return key + "={" + value.toString() + '}';
}
}
(2) MyHashMap类
package cn.edu.ucas.gqlearn;
import java.util.Arrays;
/**
* @Author: hyk
* @Date: 2020/7/22
* @version: 1.0
*/
public class MyHashMap<K,V> {
MyHashNode<K,V>[] table;
private static final int DEFAULT_CAPACITY = 16;
public MyHashMap() {
table = new MyHashNode[DEFAULT_CAPACITY];
}
public void put(K key, V value){
MyHashNode<K, V> newHashNode = new MyHashNode<>(key.hashCode(), key, value, null);
int myHash = getMyHash(key.hashCode());
if (table[myHash] == null){
table[myHash] = newHashNode;
}else{
MyHashNode<K,V> temp = table[myHash];
MyHashNode<K, V> lastHashNode = null;
while(temp != null){
if (temp.hashCode() == key.hashCode()){
temp.value = value;
break;
}else{
lastHashNode = temp;
temp = temp.next;
}
}
lastHashNode.next = newHashNode;
}
}
public V get(K key){
int myHash = getMyHash(key.hashCode());
MyHashNode<K,V> temp = table[myHash];
while(key.hashCode() != temp.hash){
temp = temp.next;
}
if (temp != null){
return temp.value;
}else{
System.out.println("查不到该对象!");
return null;
}
}
public int getMyHash(int hashCode){
int myHash = hashCode & (table.length - 1);
return myHash;
}
@Override
public String toString() {
boolean isEmpty = false;
StringBuilder sb = new StringBuilder();
sb.append("[");
for (MyHashNode<K,V> myHashNode:table) {
isEmpty = true;
while (myHashNode!= null){
sb.append(myHashNode.toString() + ",");
myHashNode = myHashNode.next;
isEmpty = false;
}
if (!isEmpty){
sb.append("\n");
}
}
sb.setCharAt(sb.length()-2,']');
return sb.toString();
}
public static void main(String[] args) {
MyHashMap<Integer, String> mhm = new MyHashMap<>();
mhm.put(1001,"刘亦菲");
mhm.put(1002,"赵丽颖");
mhm.put(1003,"杨幂");
mhm.put(1017,"赵灵儿");
mhm.put(1033,"小龙女");
System.out.println(mhm.toString());
System.out.println(mhm.get(1017));
System.out.println(mhm.get(1002));
}
}