Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Newbie - What are hashcodes?

The treehouse video didnt really go into details in it, but after some research I'm guessing it is a number used to quickly distinguish/store/retrieve objects? Please correct me if I'm wrong!

Also, I also tried reading about hashMaps/hashSets, but I can't seem to comprehend what they are used for.

1 Answer

Hashing is a large and complex topic in computer science but it basically means to reduce an arbitrary amount of data into a single number (or a fixed number of bits).

https://en.wikipedia.org/wiki/Hash_function

hashCode() gives you an integer which is computed from an object's contents (or memory address) which can be used to place the object in a hash table. One way to think of a hash table is a fixed set of numbered bins. The hash code is the bin number. (Or here the remainder hashCode() divided by the number of bins.) To retrieve an object, you just need search the object's single bin instead of all the objects in the table.

HashMap and HashSet are just implementations of Map and Set using a hash table to store their data.