Welcome back! This lesson explores hashing, a mysterious and yet incredibly useful idea that is even included directly in our programming language!
Our next lesson covers some material that is both extremely cool and very useful for real-world programming. So let’s get started! Up first—the mysterious and useful power of hashing…
Wikipedia defines a hash function:
A hash function is any function that can be used to map data of arbitrary size to fixed-size values. The values returned by a hash function are called hash values, hash codes, digests, or simply hashes.
Let’s unpack that definition together…
hashCode
hashCode
Hashing turns out to be so useful that a hash function is one of the built-in methods that every Kotlin object provides. Let’s see how that works, and how to develop hash codes for our own classes:
Are hash functions useful? Yes! Extremely! And, they are also very widely used! Let’s go through a few examples.
Hash functions are commonly used to verify downloaded files. Let’s see that in action.
Download verification is one example of an application of hash functions known as content fingerprinting. Let’s look at another: Git!
Hash functions also appear in another perhaps-unexpected place: Bitcoin mining! Let’s explore the fundamental concept of proof of work that is used to add blocks to the blockchain:
Create a public class named Course
providing a single constructor setting three private String?
properties:
department, number, and title, in that order.
Implement hashCode
using java.util.Objects
by hashing the department and number, only, in that order.
If a hash function produces the same output for two different inputs, this is known as a collision. Whether or not a hash collision is a problem depends a lot on the application. But, it turns out that hash collisions are much more common than we might imagine! Let’s see why.
Create a public class named Restaurant
providing a single primary constructor setting three private String
properties: id, name, and cuisine, in that order.
Implement hashCode
using java.util.Objects
by hashing the restaurant's id and name, only, in that order.
Need more practice? Head over to the practice page.