码迷,mamicode.com
首页 > 编程语言 > 详细

java 手工实现HashMap

时间:2019-07-20 11:37:49      阅读:96      评论:0      收藏:0      [点我收藏+]

标签:har   nod   根据   tchar   长度   节点   while   rgs   put   

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

标签:har   nod   根据   tchar   长度   节点   while   rgs   put   

原文地址:https://blog.51cto.com/14437184/2421919

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!