老师手写的HashMap算法可以了解

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));
	}

}

 

作者:赵云老师,上课代码。做的笔记

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值