数据结构11:哈希表专题

哈希表实现类HashTable

package ch15;

import java.math.BigInteger;

public class HashTable {
    private Info[] arr;

    /**
     * 默认的构造方法
     */
    public HashTable() {
        arr = new Info[100];
    }

    /**
     * 指定数组初始化大小
     */
    public HashTable(int maxSize) {
        arr = new Info[maxSize];
    }

    /**
     * 插入数据
     */
    public void insert(Info info) {
        arr[hashCode(info.getKey())] = info;
    }

    /**
     * 查找数据
     */
    public Info find(String key) {
        return arr[hashCode(key)];
    }

    public int hashCode(String key) {
//      int hashVal = 0;
//      for(int i = key.length() - 1; i >= 0; i--) {
//          int letter = key.charAt(i) - 96;
//          hashVal += letter;
//      }
//      return hashVal;

        BigInteger hashVal = new BigInteger("0");
        BigInteger pow27 = new BigInteger("1");
        for(int i = key.length() - 1; i >= 0; i--) {
            int letter = key.charAt(i) - 96;
            BigInteger letterB = new BigInteger(String.valueOf(letter));
            hashVal = hashVal.add(letterB.multiply(pow27));
            pow27 = pow27.multiply(new BigInteger(String.valueOf(27)));
        }
        return hashVal.mod(new BigInteger(String.valueOf(arr.length))).intValue();
    }
}

键值对定义类

package ch15;
/**
 * 员工信息类
 * @author Administrator
 *
 */
public class Info {
    private String key;
    private String name;

    public Info(String key, String name) {
        this.key = key;
        this.name = name;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值