自定义HashMap

自定义这个HashMap:花费了我大量的时间去研究这个基础的东西,以个人现在的水平认为HashMap、ArrayList和LinkedLsit中最难的就是HashMap,它的核心就是结合了ArrayList和LinkedList,在数组里面装放链表,由于本人现在没完备接触有关数据结构算法之类的东西,因此在链表这方面卡壳卡了良久,现在总算弄懂了,以下是我自己实现的HashMap,这也算是个人在Java学习生涯中的一个提升吧!

个人认为:难的东西是可以挑战自己提升自己的能力的。

                  基础很重要,打好基础为日后做准备!

至于月薪过万,是我在B站自学Java的时候,高琪老师所讲,若是按照这种学习态度,可以自定义HashMap独立的完成,继续学下去,抱着这种学习态度去学习,相信学出来的效果是不会差的。

/**
 * 实现节点,用于MyHashMap中
 * @author Administrator
 *
 */
public class Node<K,V> {
	int hash;
	K key;
	V value;
	Node next;
}
/**
 * 自定义HashMap,实现put方法(加size扩容)、get方法、重写toString方法、实现封装
 * @author Administrator
 *
 */
public class MyHashMap<K,V> {
	Node[] table;
	int size;
	
	//构造器
	public MyHashMap() {
		table = new Node[16];
	}
	
	public void put(K key,V value) {
		
		//解决数组扩容
		if(size==table.length) {
			Node[] newArray = new Node[(size<<1)+1];
			System.arraycopy(table, 0, newArray, 0, table.length);
			table = newArray;
		}
		
		Node newNode = new Node();
		newNode.hash = myHash(key.hashCode(),table.length);
		newNode.key = key;
		newNode.value = value;
		newNode.next = null;
		
		Node temp = table[newNode.hash];
		Node iterLast = null;
		boolean KeyRepeat = false;
		
		//如果数组为空的情况
		if(temp==null) {
			table[newNode.hash] = newNode;
		}
		//如果数组不为空的情况(hash一样),那么就要利用链表的知识了
		else {
			while(temp!=null){
				//如果key重复的,那么就要替换掉value
				if(temp.equals(key)) {
					KeyRepeat = true;
					temp.value = value;
					break;
				}else {
					//key不重复则遍历下一个
					iterLast = temp;
					temp = temp.next;
				}
			}
			if(!KeyRepeat) {
				iterLast.next = newNode; 
			}
		}
		size++;
	}
	
	public int myHash(int v,int length) {
		return v&(length-1);
	}
	
	public V get(K key) {
		int hash = myHash(key.hashCode(),table.length);
		Node temp = table[hash]; 
		Object value = null;
		while(temp!=null) {
			if(key.equals(temp.key)) {
				value = temp.value;
				break;
			}
			temp = temp.next;
		}
		return (V) value;
	}
	
	@Override
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("{");
		for(int i=0;i<table.length;i++) {
			Node temp = table[i];
			//遍历链表
			while(temp!=null) {
				sb.append(temp.key+":"+temp.value+",");
				temp = temp.next;
			}
		}
		sb.setCharAt(sb.length()-1, '}');
		return sb.toString();
	}

	public static void main(String[] args) {
		MyHashMap<Integer,String> m = new MyHashMap<>();
		m.put(10, "aa");
		m.put(20, "bb");
		m.put(30, "cc");
		m.put(53, "zz");
		m.put(69, "gg");
		m.put(85, "kk");
		System.out.println(m);
		System.out.println(m.get(53));
		System.out.println(m.get(69));
		System.out.println(m.get(85));
	}
}

猜你喜欢

转载自blog.csdn.net/szlg510027010/article/details/82355088