java-如何使用多个值将哈希值加倍

时间:2018-10-23 11:13:33

标签: java data-structures double-hashing

我正在寻找一种创建具有多个值的双哈希的方法。我已经能够创建以下双重哈希。我现在想用多个值来做。例如,诸如firstname和surname之类的东西,然后能够从get或find方法

检索给the的值。
public class HashTableDoubleHashing {

String[] hashArray;
int arraySize;
int size = 0;

public HashTableDoubleHashing(int numTotaal) {

    if (isPrime(numTotaal)) {
        hashArray = new String[numTotaal];
        arraySize = numTotaal;
    } else {
        int primeCount = getNextPrime(numTotaal);
        hashArray = new String[primeCount];
        arraySize = primeCount;
       // System.out.println("Hash table size given " + numTotaal + " in not a prime.");
      //  System.out.println("Hash table size is changed to: " + primeCount);
    }
}

private boolean isPrime(int num) {
    for (int i = 2; i * i <= num; i++) {
        if (num % i == 0) {
            return false;
        }
    }
    return true;
}

private int getNextPrime(int minNumber) {
    for (int i = minNumber; true; i++) {
        if (isPrime(i)) {
            return i;
        }
    }
}

private int hashFunction1(String word) {
    int hashVal = word.hashCode();
    hashVal = hashVal % arraySize;
    if (hashVal < 0) {
        hashVal += arraySize;
    }
    return hashVal;
}

private int hasFuntion2(String word) {
    int hashVal = word.hashCode();
    hashVal = hashVal % arraySize;
    if (hashVal < 0) {
        hashVal += arraySize;
    }

    return 3 - hashVal % 3; 
}

public void insert(String word) {
    int hashValue = hashFunction1(word);
    int stepSize = hasFuntion2(word);

    while (hashArray[hashValue] != null) {
        hashValue = hashValue + stepSize;
        hashValue = hashValue % arraySize;
    }

    hashArray[hashValue] = word;
    System.out.println("inserted word: " + word);
    size++;
}

public String find(String word) {
    int hashValue = hashFunction1(word);
    int stepSize = hasFuntion2(word);

    while (hashArray[hashValue] != null) {
        if (hashArray[hashValue].equals(word)) {
            return hashArray[hashValue];
        }
        hashValue = hashValue + stepSize;
        hashValue = hashValue % arraySize;
    }

    return hashArray[hashValue];

}

public static void main(String[] args) {
    HashTableDoubleHashing table = new HashTableDoubleHashing(10);
    table.insert("Rice");
    table.insert("Cola");
    table.insert("Doritos");
    table.insert("Sushi");
    table.insert("Pancakes");

    System.out.println("------------------Find food------------------");
    System.out.println(table.find("Rice"));
    System.out.println(table.find("Pizza"));
    System.out.println(table.find("Sushi"));
}

0 个答案:

没有答案