手动实现HashMap1_基本结构_put存储键值对

版权声明: https://blog.csdn.net/weixin_40072979/article/details/82932649
package com.jianshun;

//用于SxtHashMap中
public class Node2 {

	int hash;
	Object key;
	Object value;
	Node2 next;
}
package com.jianshun;
/**
 * 自定义一个HashMap
 * @author Administrator
 *
 */
public class SxtHashMap01 {

	Node2[] table; //位桶数组 bucket array
	int size;  //存放键值对的个数
	
	public SxtHashMap01(){
		table = new Node2[16];  // 长度一般指定为2的整数幂
	}
	
	//向HashMap中存储数据
	public void put(Object key,Object value){
		//定义了新的节点对象
		Node2 newNode = new Node2();
		newNode.hash= myHash(key.hashCode(), table.length);
		newNode.key = key;
		newNode.value = value;
		newNode.next = null;
		
		//将链表与数组对应起来
		Node2 temp = table[newNode.hash];
		if(temp ==null){
			//数组此处为空,直接将数组放进去,
			table[newNode.hash] = newNode;
		}else{
			//此处数组元素不为空,则遍历对应链表
			
		}
		
	}
	
	public int myHash(int v,int length){//v 为根据 key hashCode()计算出来的哈希吗
		System.out.println("hash in myHash:"+(v&(length-1)));//直接位运算,效率高
		System.out.println("hash in myHash:"+(v%(length-1)));//取模运算,效率低
		return v&(length-1);
	}
	
	public static void main(String[] args) {
		SxtHashMap01 m =new SxtHashMap01();
		m.put(10, "aa");
		m.put(20, "bb");
		m.put(30, "cc");
		System.out.println(m);
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_40072979/article/details/82932649