Scott
Scott

Reputation: 455

Hashing objects in Java?

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

Upvotes: 3

Views: 1625

Answers (2)

Joachim Sauer
Joachim Sauer

Reputation: 308001

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

Upvotes: 2

Ajinkya
Ajinkya

Reputation: 22710

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;
}

Upvotes: 2

Related Questions