Merl's Blog

Java Maps

I have been spoiled by Clojure and Python. The dynamically typed languages so far are my favorite. They help make life easier for me, which I am all about!

I do however have to learn for the rest of my life, so it would be wise to learn and get better at Java.

I was trying to create a hash map in Java. But I have not been making the map as succinct as it should be.

public void put(Key key, Value value) {
   int bucket = key.hashCode() % numberOfBuckets;
   Pair<Key, Value> pair = table[bucket];


   if (pair == null) {
       table[bucket] = new Pair<Key, Value>(key, value);
   } else {
       while (pair.next != null) {
           if (pair.isKey(key)) {
               pair.value = value;
               return;
           }
           pair = pair.next;
       }
       if (pair.getKey().equals(key)) {
           pair.setValue(value);
           return;
       }
       pair.next = new Pair<Key, Value>(key, value);
   }
}

This is what was written before. I should be able to use Linked lists and array lists to make life easier for myself.

Here I am recreating what a linked list already does. I need to implement what the list already does into this code. As well as just refactor in general.

Here is my current attempt so far.

public void put(Key key, Value value) {
   int bucket = key.hashCode() % numberOfBuckets;

   for (Pair<Key, Value> pair : list) {
       if (pair.getKey().equals(key)) {
           pair.setValue(value);
           return;
       }
   }
   list.add(new Pair<>(key, value));
}

Sometimes the simpler things take longer to put down.

Slowly but surely I will get better at Java.

Best,

Merl