32 Hashing
33 Chapter: The Magic Bakery: An Adventure in Hashing with Dart
“Step into the magic bakery of Dart, where each sumptuous treat is more unique than the last, just like our hashing concept. What’s that? You’ve never heard of ‘hashing’ in a bakery? Oh, my friend, you’re in for a delightful surprise! Welcome to the world where computer science meets the irresistible aroma of baked goodies!”
33.1 1. What is Hashing?
Imagine you walk into a bakery filled with mouthwatering pastries. But here’s the thing - each pastry is one of a kind. How do we distinguish them all? Easy! The magic baker uses a special technique: each pastry is sprinkled with a unique mix of magic sugar that assigns a unique number, known as a ‘hash code’. Just like our pastries, objects in Dart can have their own hash code too.
void main() {
var cupcake = 'Strawberry Cupcake';
.hashCode); // Outputs a unique number, the hash code of 'Strawberry Cupcake'
print(cupcake }
Here, hashCode
is like our magic sugar sprinkler, creating a unique hash code for the Strawberry Cupcake
.
33.2 2. Why is Hashing Important?
Back in our bakery, imagine you have hundreds of unique pastries. You need to find a specific one - a delectable Lemon Tart
. How would you find it amongst all these treats without tasting each one? The answer is the magic sugar, or hash code! It helps to quickly find and identify our Lemon Tart
. Similarly, in programming, hashing helps us locate and access data swiftly and efficiently.
void main() {
var magicBakery = { 'Strawberry Cupcake'.hashCode : 'Strawberry Cupcake', 'Lemon Tart'.hashCode : 'Lemon Tart' };
var desiredTreatHashCode = 'Lemon Tart'.hashCode;
// Outputs 'Lemon Tart'
print(magicBakery[desiredTreatHashCode]); }
In the code above, magicBakery
is our Dart map, acting as the bakery catalogue. Each pastry is associated with its unique hash code. To find the Lemon Tart
, we just look for its hash code!