The following is the inside of a method for collision detection while inserting into my own hash table. I’m working with small test numbers and trying to get my logic right, the variable hash is set to 0 and the table.length is 10.
else
{
//problem here
int initial=(hash-1)%table.length;
while (table[hash]!=null)
{
hash+=1;
System.out.println(initial);
if (hash==table.length)
{
hash=0;
}
if (hash==initial)
{
System.out.println("FULL!");
break;
}
The variable initial needs to be the index BEFORE whatever my current one is (hash). My problem is if hash is 0, initial needs to be set to 9. I thought this would work but I’m getting -1 when hash is set to 0 for example. The first IF statement loops back to the first index if you for example started in the middle at 5 or something, the second one is for for when you’ve checked all indexes and they’re all full.
Since you use
%, there is no risk of overflow, so you can just change the line toto get around this problem.