We’ve seen how to use maps. Now let’s explore how to implement one.
They may seem mysterious, but as we create our own map we’ll see one way that they can work, and understand more about the inherent performance tradeoffs.
Maps are incredibly useful. But they are also straightforward to implement!
Let’s create our own simple
Map implementation, one step at a time.
We’ll use an approach called a hash table, and wind up with something that is an interesting hybrid between an array and a linked list.
First, let’s set up our
Map class and stub out the methods that we’ll need to implement.
We’ll also create a few helper inner classes that we will use along the way.
Before we continue, let’s also examine what we’re building visually to hopefully help us gain some intuition.
Second, we’ll implement
It’s hard to tell if the
Map is working yet, but we’ll add a size method to help.
Next we’ll implement
get and then be able to test out our
Finally we’ll consider the performance of our map in several different dimensions.
I bet you were wondering: Did we miss the debugging challenge? Nope!
Create a public, non-final class named
Partitioner. Implement a public static method
int partition(int values) that returns the input array partitioned using the first
array value as the pivot. All values smaller than the pivot should precede it in the array,
and all values larger than or equal to the pivot should follow it. Your method should return the
index of the pivot value. If the array is
null or empty you should return -1.
Need more practice? Head over to the practice page.