java 手工实现HashMap

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 手工实现HashMap相关的知识,希望对你有一定的参考价值。

import java.util.HashMap; import java.util.Map; public class test<K,V> node[] table;//核心位桶数组 int size; //存放的键值对数 public test() table =new node[16]; //长度是2的整数幂 public void put(Object key,Object value) //定义节点对象 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]; boolean flag=false; node nodelast=null;//正在遍历的最后一个元素 if(temp==null) //数组此处为空,则直接放新节点 table[newnode.hash]=newnode; else //若不为空,则遍历链表,如果重复则替换,不重复则添加到后面 while(temp!=null) if(temp.key.equals(key)) //如果键重复,只需要改变value flag=true; System.out.println("key重复了"); temp.value=value; break; else nodelast=temp; //当temp为空时,保存最后一个元素 temp=temp.next; if(flag==false) nodelast.next=newnode; size++; public int myHash(int v,int length) //得到Hash值,根据传入键值和数组长度计算Hash值 System.out.println(v&(length-1)); return v&(length-1); public V get(K key) //获得键对应的值,通过键的Hash值找到数组对应位置,再遍历链表查找键对应的值 int hash=myHash(key.hashCode(),table.length); V value=null; if(table[hash]!=null) node temp=table[hash]; while(temp!=null) if(temp.key.equals(key)) value=(V) temp.value; break; temp=temp.next; return (V)value; public int getSize() //返回键值对个数 return size; public String toString() //重写toString方法 StringBuilder s= new StringBuilder(); s.append(""); for(int i=0;i<table.length;i++) //遍历数组 node temp=table[i]; while(temp!=null) //遍历数组对应位置的链表 s.append(temp.key+":"+temp.value+","); temp=temp.next; //HashMap存储是相当于在数组的对应位置存储一个链表 s.setCharAt(s.length()-1,‘‘); return s.toString(); public static void main(String[] args) test<Integer,String> t =new test<>(); t.put(10, "ad"); t.put(19, "aa"); t.put(8, "add"); t.put(3,"ff"); System.out.println(t); System.out.println(t.get(19)); System.out.println(t.getSize());

以上是关于java 手工实现HashMap的主要内容,如果未能解决你的问题,请参考以下文章

java 手工实现HashSet

java 手工实现ArrayList版本2

java 手工实现HashMap

java 手工实现LinkedList容器

java容器---------手工实现Linkedlist 链表

java 手工实现ArrayList版本一