1

I have to code a perfect Hashing table for a homework, but I'm struggling to understand:

What's the difference between the return of hashCode() and a key in a hashTable since I have to implement the methode getKey() but I only know that the index of an object x is given by ((a * x.hashCode() + b) mod p) mod m when a and b are random integers, p a prime number and m the size of the table.

Since the index is given by H(key), that means that x.hashCode() is the key in my opinion, but I'm not sure because the key and the value (only integers) are the same.

takendarkk
  • 3,347
  • 8
  • 25
  • 37
David
  • 25
  • 3

1 Answers1

1

hashcode() method produces the expected result of applying the object's hashing method on a specific instance, whereas the key is the object itself.

Bear in mind the object can be another complex/composite object ( say another HashMap). As long as it has a reasonable implementation of hashcode() and equals() , it'll work just fine.

If two instances produce the same hashcode() result and equals() compares according to that result ( setting aside type checks, but they're of-course, also part of the test), the objects are deemed equal/identical.

This gets really interesting once you start working with TreeMaps ( where equality is not based on hashcode/equality, but rather on ordering, Comparables and Comparators)

Sheinbergon
  • 2,875
  • 1
  • 15
  • 26
  • 1
    This is why it's important that `equals`, `hashCode`, and `compareTo` (if used) must be consistent. Ideally so will `toString`. – Lew Bloch Mar 14 '17 at 23:24