package com.how2java.pojo;
public class MyhashMap<K,V> {
private static final int DEFAULT_SIZE=1<<4;//默认大小一定要用2的整数倍,算哈希值的时候减小hash冲突
private Entry<K,V>[] data;//数组
private int capacity;//负载因子
private int size;//大小
//构造函数
public MyhashMap(){
this(DEFAULT_SIZE);//调用有参构造函数
}
//构造函数
public MyhashMap(int setSize){
if(setSize>0) {
data=new Entry[setSize];
size=0;
this.capacity=setSize;
}else {
System.out.println("error");
}
}
//计算hash值
private int hash(K key) {
int h=0;
if(key==null)h=0;
else {
h=key.hashCode()^(h>>>16);//hash计算
}
return h%capacity;
}
//put值
public void put(K key,V value) {
if(key==null)System.out.println("error");
int hash=hash(key);
Entry<K,V> nE=new Entry<K, V>(key, value, null);
Entry<K,V> mE=data[hash];
while(mE!=null) {
if(mE.key.equals(key)) {
mE.value=value;
return;
}
mE=mE.next;//赋值
}
nE.next=data[hash];
data[hash]=nE;
size++;
}
public V get(K key) {
int hash=hash(key);
Entry<K, V> entry=data[hash];
while(entry!=null) {
if(entry.key.equals(key)) {
return entry.value;
}
}
return null;
}
//扩容是红黑树算法
//定义数据结构
private class Entry<K,V> {
K key;
V value;
Entry<K,V> next;//链表
Entry(K key,V value,Entry<K,V> next) {
this.key=key;
this.value=value;
this.next=next;
}
}
public static void main(String[] args) {
MyhashMap<Object, Object> myhashMap = new MyhashMap<>();
myhashMap.put(1, 33);
myhashMap.put(2, 34);
myhashMap.put(2, 12);
System.out.println(myhashMap.get(1));
System.out.println(myhashMap.get(2));
}
}
作者:赵云老师,上课代码。做的笔记