Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hashing objects in Java?

Tags:

java

hash

This is a homework question so I'm not looking for specific implementation but more an understanding of how to implement the following:

I have to create a hash table class, I understand how a hash table works but I am confused about how it actually hashes objects. In the examples we've seen we generally see integers get stored in a hash table (for simplicity) and they are hashed using an algorithm such as value%10.

I'm fine with this but confused about the following. We have been asked to write a class that can take any object and provide methods for insertion etc. I'm not sure how I can call Object%10 considering I can't just find the modulus of an object. With this in mind given I'm not to know what sort of object a user could pass to this class (it could be one they have written themselves) how are you expected to write a hash function for all possible objects? Am I missing something here?

I've tried Googling but I'm not exactly sure what to Google so I'm coming up with not much, thanks

like image 873
Scott Avatar asked Jan 25 '26 19:01

Scott


2 Answers

Hashcode doesnt always have to be value%10, In case of object it is a number derived using state of object ie attributes of object.
If you class like

public class MyClass {
    int a;
    int b;
}

then Hashcode can be simple as

public int hashCode() {
    int result = a + b;
    return result;
}
like image 96
Ajinkya Avatar answered Jan 27 '26 07:01

Ajinkya


Check the methods of the Object class. Every object in Java has those methods. See if one of them can help you.

like image 41
Joachim Sauer Avatar answered Jan 27 '26 09:01

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!