package 手写哈希表;
public class HashMap_plus<K,V>{
@SuppressWarnings("rawtypes")
Node1[] tableNodes;// 建立装链表的桶
int size=0;
public HashMap_plus(){
tableNodes = new Node1[16];// 长度为2的整数次幂
}
@SuppressWarnings("unchecked")
public void put(K key, V value) {
Node1 xNode = null;
Node1 node = new Node1();
int t = Myhash(key.hashCode(), tableNodes.length);
node.hash = t;
node.valueObject = value;
node.key = key;
if (tableNodes[t] == null) {
tableNodes[t] = node;
size++;
} else {
Node1 tempNode = tableNodes[t];
while (tempNode!= null) {
if (tempNode.key.equals(key)) {
tempNode.valueObject=value;
t=-1;//声明这块key值相同所以替换了value
break;
} else {
xNode=tempNode;
tempNode = tempNode.nextNode;
}
}
if(t!=-1)
{xNode.nextNode = node;//之前这样搞不行,这样搞就是将值给到了tempNode,
size++;} //没有声明nextNode是它,所以要么有个ifelse
//再一次判断key,要么就再用一个NOde来跟随tempNode
}
}
public String toString() {
StringBuilder s = new StringBuilder();// 可变字符串
// Node node=new Node();
//Node node;
s.append("[");
// Node[] node;
// node=tableNodes;
// for(int i=0;i<tableNodes.length;i++)
// for(;node[i]!=null;node[i]=node[i].nextNode)
// s.append(node[i].valueObject + ",");
// s.setCharAt(s.length() - 1, ']');
//上边这样整,因为node指向tablenode之后,他俩有一样的意义了
//append每次都是把node数组中的值给拿来而不是复制,所以这样就不行
Node1 node;
for (int i=0; i<tableNodes.length; i++)
{node=tableNodes[i];
for(;node!=null;node=node.nextNode)
s.append(node.valueObject + ",");}
s.setCharAt(s.length() - 1, ']');
return s.toString();
}
public int Myhash(int v, int length) {
//System.out.println("hash 值------" + (v & (length - 1)));
//直接位运算,效率高
return v & (length - 1);
}
@SuppressWarnings("unchecked")
public V get(K key) {
int hash=Myhash(key.hashCode(),tableNodes.length);
V valueObject=null;
if(tableNodes[hash]!=null) {
Node1 tNode=tableNodes[hash];
//System.out.println(tNode.valueObject);
while(tNode!=null)
{
if(tNode.key.equals(key))
{
valueObject=(V)tNode.valueObject;
break;
}else
{
tNode=tNode.nextNode;
}
}
}return valueObject;
}
public static void main(String[] args) {
HashMap_plus<Integer, String> sFalse = new HashMap_plus<>();
sFalse.put(1, "aa");
sFalse.put(2, "bb");
sFalse.put(3, "cc");
sFalse.put(4, "cd");
System.out.println(sFalse.get(2));
System.out.println(sFalse.get(1));
System.out.println(sFalse.toString());
System.out.println(sFalse.toString());
System.out.println(sFalse.get(3));
System.out.println(sFalse.get(1));
System.out.println(sFalse.size);
//一下是测试找到相等哈希值
//16-0 17-1 18-2 19-3
// for(int i=0;i<100;i++)
// {
// System.out.println(i+"----"+sFalse.Myhash(i, 16));
//
// }
}
}
class Node1<K,V> {
K key;
V valueObject;
int hash;
Node1 nextNode;
}
努力学习的计算机小白
发布了4 篇原创文章 · 获赞 0 · 访问量 52
私信
关注