Kotlinlearncs.online LogoJava

Hashing

println("you".hashCode())
println("you are not".hashCode())
println("you are not alone!".hashCode())

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…

What is Hashing?
What is 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…

Kotlin’s hashCode
Kotlin’s 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:

// hashCode Examples

How Are Hashes Used?
How Are Hashes Used?

Are hash functions useful? Yes! Extremely! And, they are also very widely used! Let’s go through a few examples.

Download Verification
Download Verification

Hash functions are commonly used to verify downloaded files. Let’s see that in action.

Content Fingerprinting
Content Fingerprinting

Download verification is one example of an application of hash functions known as content fingerprinting. Let’s look at another: Git!

Proof of Work
Proof of Work

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:

// Proof-of-Work Example

Practice: Course Hash Code

Created By: Geoffrey Challen
/ Version: 2020.10.0

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.

Hash Collisions
Hash Collisions

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.

Homework: Restaurant Hash Code

Created By: Geoffrey Challen
/ Version: 2021.11.0

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.

More Practice

Need more practice? Head over to the practice page.