Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement own hashing function for strings?

So this is the default algorithm that generates the hashcode for Strings:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

However, I wanna use something different and much more simple like adding the ASCII values of each character and then adding them all up.

How do I make it so that it uses the algorithm I created, instead of using the default one when I use the put() method for hashtables?

As of now I don't know what to do other than implementing a hash table from scratch.

like image 953
Nezrik Avatar asked Aug 26 '26 14:08

Nezrik


1 Answers

Create a new class, and use String type field in it. For example:

public class MyString {
    private final String value;

    public MyString(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        MyString myString = (MyString) o;
        return Objects.equals(value, myString.value);
    }

    @Override
    public int hashCode() {
        // use your own implementation
        return value.codePoints().sum();
    }
}

Add equals() and hashCode() methods with @Override annotation. Note: here hashCode() operates only with ASCII values.

After that, you will be able to use new class objects in the desired data structure. Here you can find a detailed explanation of these methods and a contract between equals() and hashCode().

like image 140
Albina Avatar answered Aug 28 '26 02:08

Albina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!