数据结构实战java实现hash表

来源:互联网 发布:java工程师所属部门 编辑:程序博客网 时间:2024/05/20 03:37

此方法参考自《数据结构与算法-java实现》
我采用分离链接法来避免数据冲突。

hash表概述

通过hash函数将字符串,或者一个数字,经过整理变为数组的下标。
这样我们就可以得到一个时间复杂度为1的表。
而分离链接法
这里写图片描述
就是如果有俩个或以上的不同的key值hash化计算后结果相同。将这些值放在链表中。

实现

//使用分离链接法的hashtable 实现public class MyHashTable<AnyType> {    public static void main(String[] args) {        MyHashTable test = new MyHashTable();        //System.out.println(test.theLists.length);        test.insert(12);        test.insert(13);        System.out.println(test.contains(12));    }    //初始化hashtable    public MyHashTable() {        this(DEFAULT_TABLE_SIZE);      }    //实际的构造方法 1构造一个链表组,2    public MyHashTable(int size) {        theLists = new LinkedList[ nextPrime( size)];        for ( int i = 0; i < theLists.length; i++ )            theLists[ i ] = new LinkedList<AnyType>();    }    // 放入新的key值在hash表中    public void insert( AnyType value) {        LinkedList<AnyType>  whichList = theLists[ myhash( value )];        if ( !whichList.contains( value )) {            whichList.add(value);            if ( ++currentSize > theLists.length)                System.out.println("hash表满了");        }    }    // 移除key值    public void remove( AnyType value) {        LinkedList<AnyType>  whichList = theLists[ myhash( value )];        if ( whichList.contains( value )) {            whichList.remove(value);            currentSize--;                       }             }    //判断是否有这个key    public boolean contains( AnyType value) {        LinkedList<AnyType>  whichList = theLists[ myhash( value )];        return whichList.contains(value);       }    //清空hash表    public void makeEmpty() {        for (int i = 0; i < theLists.length; i++)            theLists[ i ].clear();        currentSize = 0;    }    private static final int DEFAULT_TABLE_SIZE = 101;    private LinkedList<AnyType> [] theLists;    private int currentSize;    //此函数将value 转化为数组下标    private int myhash(AnyType value) {        int hashVal = value.hashCode();        hashVal %= theLists.length;        if (hashVal < 0 )            hashVal += theLists.length;        return hashVal;    }    //如果参数是素数直接返回参数,否则返回下一个素数    private static int nextPrime( int n ) {        while (!isPrime( n ))            n += 1;        return n;    }    private static boolean isPrime( int n ) {        double localVal;        int count = 2;        localVal = Math.sqrt( n );        while ( count < localVal ) {            if ( localVal % count == 0)                return false;            else                count++;                    }        return true;    }}