I am in the process of remaking/refactoring my previous HashMap in Java.
I decided to use my old previous tests and begin the process of Test Driven Design anew. It was interesting because I did have some curve balls in my tests that I had to figure out. One of them was having null as a key and still using that as a way to store a value.
What was interesting was my solution to those tests I had written before. Instead of having to create a literal hashmap with an array with linked lists in the buckets, I was able to make every test pass using 2 arrays.
``java
Key key;
Value value;
List
public void put(Key key, Value value) {
this.key = key;
this.value = value;
list1.add(key);
list2.add(value);
}
I used this simple method to place the pieces into their respective arrays.
Afterwards I used this for loop to find the correct key. Once that key was found, I used the same index to find the value associated with that key.
```java
public Object get(Key key) {
if (this.key == key) {
return value;
} else {
for (int i = 0; i< list1.size(); i++){
if (key.equals(list1.get(i))){
return list2.get(i);
}
}
}
return null;
}
The same process was done in remove.
I find it interesting that using TDD you can come to a solution that you never would have imagined otherwise.
This is fascinating, however I am supposed to create an actual hashmap so this doesn’t place me where I need to be.
It is an interesting side quest to learn from.
Best,
Merl