I am creating a hash function by myself for my university assignment. My hash function works something like this ... It will take a string as input and add the ASCII values of every character into a integer variable named sum. This is done in the function named hash_func. Then in the function named MYHashfunc I have used recursion to decrease the value of sum such that it can be a value lesser than the size of the array in which I will store data in using my hash function. Since I am using seperate chaining method to resolve collisions , I used a LinkedList array. But I am getting a stack overflow error when the function hash_func is called inside MYhashfunc. The code is given below:-
package hashfunction;
import java.util.LinkedList;
import java.util.Scanner;
public class Hashfunction {
public static int MyhashFUNC(String str,int A){
int X=0;
int sum = hash_func(str);
if(sum<A)
return sum;
else{
X = X+sum%10;
sum /= 10;
return(MyhashFUNC(str, A));
}
}
public static int hash_func(String str) {
int sum = 0;
int len = str.length();
for (int i = 0; i < len; i++) {
if (str.charAt(i) >= '0' && str.charAt(i) <= '9') {
sum += (int) str.charAt(i);
} else if (str.charAt(i) >= 'a' && str.charAt(i) <= 'z' ||
str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
sum += (int) str.charAt(i);
}
}
return sum;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N;
int z;
N = sc.nextInt();
String[] str_array = new String[N];
LinkedList<String>[] l_list = new LinkedList[N];
for (int i = 0; i < N; i++) {
l_list[i] = new LinkedList<String>();
}
for (int i = 0; i < N; i++) {
str_array[i] = sc.next();
}
for (int i = 0; i < N; i++) {
z = MyhashFUNC(str_array[i],N);
if(l_list[z].peek()!="-1"){
l_list[z].set(z, str_array[i]);
}
else{
l_list[z].add(str_array[i]);
}
}
for (int i = 0; i < N; i++) {
int size = l_list[i].size();
for (int j = 0; j < size; j++) {
System.out.println(l_list[i].get(j));
}
}
}
}
In the method
public static int MyhashFUNC(String str,int A){
int X=0;
int sum = hash_func(str);
if(sum<A)
return sum;
else{
X = X+sum%10;
sum /= 10;
return(MyhashFUNC(str, A)); // Call again MyhashFUNC with same parameters
}
}
if sum >= a
you enter the else
block and you call again the same method with the same parameters. This will generate the StackOverFlow
.