自己实现HashMap
/**
* hashmap的demo
* @author cuiyc
* @version 1.0
* @date 2021/6/5 22:28
*/
public class HashMapDemo {
public static void main(String[] args) {
Map<String,String> hashmap=new HashMap<>();
MyHashMap map=new MyHashMap();
map.put("k1","v1");
map.put("k2","v2");
System.out.println("map的长度是,"+map.size);
System.out.println("k2的value是,"+map.get("k2"));
System.out.println("k1的value是,"+map.get("k1"));
}
private static class MyHashMap{
private int size;
LinkedList[] array =new LinkedList[999];
public MyHashMap(){}
public MyHashMap(int size){
this.size=size;
}
//计算key的hashcode值
final int hash(Object key){
int h;
return (key==null)?0:(h=key.hashCode())^(h>>>16);
}
//对数组的长度取模,得到应该存入的位置
final int mode(int h){
return h/array.length;
}
//得到size的值
public int getSize(){
return size;
}
//put方法
public void put(Object key,Object value){
//先把key 和 value放入entry对象中
MyEntry myEntry=new MyEntry(key,value);
//根据key值计算出hashcode值,然后得到应当在数组中存放的位置
int hashValue=hash(key);
//然后拿到hahscode值后,再和数组的长度取模计算出再数组中的一个位置
hashValue=mode(hashValue);
//若该位置为空,则直接添加链表
if(array[hashValue]==null){
LinkedList linkedList=new LinkedList();
linkedList.add(myEntry);
array[hashValue]=linkedList;
}else {
//否则,该位置是已经相同的key值,则需要遍历到key值的entry,然后更新。
for (int i = 0; i < array[hashValue].size(); i++) {
MyEntry myentry= (MyEntry) array[hashValue].get(i);
if(key.equals(myentry.getKey())){
myentry.value=value;
}else {
array[hashValue].add(myEntry);
}
}
}
size++;
}
//get方法
public Object get(Object Key){
int hashCode=mode(Key.hashCode());
if(array[hashCode]!=null){
for (int i = 0; i < array[hashCode].size(); i++) {
MyEntry myEntry= (MyEntry) array[hashCode].get(i);
if(Key.equals(myEntry.getKey())){
return myEntry.value;
}
}
}
return null;
}
}
//Entry数据结构
private static class MyEntry<K,V> implements Map.Entry<K,V>{
int hash;
final K key;
V value;
MyEntry<K,V> next;
MyEntry(int hash,K key,V value,MyEntry<K,V> next){
this.hash=hash;
this.key=key;this.value=value;this.next=next;
}
public MyEntry(K key,V value){
this.key=key;this.value=value;
}
@Override
public K getKey() {
return key;
}
@Override
public V getValue() {
return value;
}
@Override
public V setValue(V newValue) {
V oldValue=value;
value=newValue;
return oldValue;
}
@Override
public final boolean equals(Object o) {
if (o == this){
return true;
}
if (o instanceof Map.Entry) {
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
if (Objects.equals(key, e.getKey()) &&
Objects.equals(value, e.getValue())){
return true;
}
}
return false;
}
@Override
public final int hashCode() {
return Objects.hashCode(key) ^ Objects.hashCode(value);
}
}
}
作者:RichardCui
出处:https://www.cnblogs.com/yachao1120/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。该文章也同时发布在我的独立博客中-RichardCuiBlog。

浙公网安备 33010602011771号