Good Hash Function for Strings

0 votes

I'm trying to think of a good hash function for strings. And I think it might be a good idea, to sum up the unicode values for the first five characters in the string (assuming it has five, otherwise stop where it ends). Would that be a good?

Jul 19, 2018 in Java by Daisy
• 8,110 points

1 answer to this question.

0 votes

Usually hashes wouldn't do sums, otherwise, stop and pots will have the same hash.

And you wouldn't limit it to the first n characters because otherwise house and houses would have the same hash.

Generally, hashes take values and multiply it by a prime number. So you can probably refer this:

int hash = 7;
for (int i = 0; i < strlen; i++) 
    hash = hash*31 + charAt(i);
answered Jul 19, 2018 by Akrati
• 960 points

Related Questions In Java

0 votes
3 answers

How to check whether a string is empty or not? Is there a function for this?

str != null && str.length() != 0 alternatively str ...READ MORE

answered Sep 11, 2018 in Java by Sushmita
• 6,900 points
0 votes
1 answer

What is the concept of Immutability for strings in Java ? Why are strings immutable ?

According to Effective Java, chapter 4, page 73, ...READ MORE

answered May 11, 2018 in Java by Rishabh
• 3,620 points
0 votes
5 answers

How to compare Strings in Java?

String fooString1 = new String("foo"); String fooString2 = ...READ MORE

answered Jul 12, 2018 in Java by Daisy
• 8,110 points
0 votes
1 answer

I am learning looping statements. Can you tell me how 'for-each' works in Java?

While programming we often write code that ...READ MORE

answered Apr 17, 2018 in Java by Rishabh
• 3,620 points
+1 vote
1 answer

concat() vs “+” operator : In Java for String concatenation

Basically, there are two important differences between ...READ MORE

answered Apr 27, 2018 in Java by Rishabh
• 3,620 points
0 votes
2 answers

How is hashmap different from hashtable?

HashMap and HashTable: 1) Hashtable and Hashmap implement ...READ MORE

answered Aug 1, 2018 in Java by samarth295
• 2,220 points
0 votes
1 answer

What are the differences between a HashMap and a Hashtable in Java?

There are several differences between HashMap and Hashtable in Java: Hashtable is synchronized, whereas HashMap is ...READ MORE

answered Dec 21, 2020 in Java by Gitika
• 65,930 points
+5 votes
4 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,450 points

edited Nov 6, 2018 by Omkar 45,776 views
+1 vote
1 answer

How to handle drop downs using Selenium WebDriver in Java

First, find an XPath which will return ...READ MORE

answered Mar 27, 2018 in Selenium by nsv999
• 5,520 points
0 votes
1 answer

What are the practical uses for AtomicInteger?

There are two main uses of AtomicInteger: As an ...READ MORE

answered Jul 18, 2018 in Java by Akrati
• 960 points