要避免哈希冲突,使用哈希桶
代码如下
// 哈希桶的简单实现 // key-value 模型 public class HashBucket { private static class Node { private int key; private int value; Node next; public Node(int key, int value) { this.key = key; this.value = value; } } private Node[] array; private int size; // 当前的数据个数 private static final double LOAD_FACTOR = 0.75; private static final int DEFAULT_SIZE = 8;//默认桶的大小 public int put(int key, int value) { int index = key % array.length; Node cur = array[index]; while (cur != null) { if (cur.key == key) { return key; } cur = cur.next; } Node node = new Node(key, value); node.next = array[index]; array[index] = node; size++; double loadFactor=loadFactor(); if(loadFactor>LOAD_FACTOR){ resize(); } return -1; } private void resize() { //扩容意味着重新哈希 Node[] newArray=new Node[2*array.length]; for(int i=0;i<array.length;i++){ Node cur=array[i]; while(cur!=null){ Node curNext=cur.next;//记录一下,因为是在重新哈希,所以下一个结点会出现找不到的情况 int index=cur.key%newArray.length; cur.next=newArray[i]; newArray[i]=cur; cur=curNext; } } } // write code here // // private double loadFactor() { return size * 1.0 / array.length; } public int get(int key){ int index=key%array.length; Node cur=array[index]; while(cur!=null){ if(cur.key==key){ return cur.key; } cur=cur.next; } return -1; } }
当对象为引用类型的话,就用泛型实现。代码如下
//泛型哈希桶的实现 public class HashBuck2<K,V> { private static class Node<K, V> { private K key; private V value; Node<K, V> next; public Node(K key, V value) { this.key = key; this.value = value; } } public Node<K,V>[] array=(Node<K,V>[])new Node[10]; public int size; public void put(K key, V value) { int hash = key.hashCode(); int index = hash % array.length;//自己写引用类型的时候记得equals和hashcode方法 Node cur = array[index]; while (cur != null) { if (cur.key.equals(key)) { return; } cur = cur.next; } Node<K, V> node = new Node<>(key, value); node.next = array[index]; array[index] = node; size++; } public V get(K key){ int hash=key.hashCode(); int index=hash%array.length; Node<K,V> cur =array[index]; while(cur!=null){ if(cur.key.equals(key)){ return cur.value; } cur=cur.next; } return null; } }
泛型实现的话,要记得写hashcode和equals方法,因为使用哈希的时候要比较key的值,然后确定index的时候必须是整数,所以要用hashcode转换