简单的hash算法

 /**
     * 散列
     * 将字符串中字符的ASCII码值加起来
     * 但是这个算法存在问题
     * 如何均匀得分布4个字符长度的字符串在2000的table中,
     * 一个ASCII字符的值最多是127,因此散列函数只能在0~127*4中分布
     * 思路:可以分段存放,0~500,501~1000,1001~1500,1501~2000
     *
     * @param key
     * @param tableSize
     * @return
     */
    public static int hash(String key, int tableSize) {
        int hashVal = 0;
        for (int i = 0; i < key.length(); i++) {
            hashVal += key.charAt(i);
        }
        return hashVal % tableSize;
    }

    public static int hash2(String key, int tableSize) {
        return (key.charAt(0) + key.charAt(1)  + key.charAt(2) + key.charAt(3) + 1500) % tableSize;
    }

    @org.junit.Test
    public void testHash() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("test" + i + ":" + hash2("test" + i, 1000));
        }
    }

你可能感兴趣的:(算法)