数据结构实战java实现hash表

此方法参考自《数据结构与算法-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;

    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值