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.
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().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With