userimage

How to create my own custom hashmap using java code

How to create my own custom hashmap using java code with efficient way.

userimage

try below code:


package com.test.self;

import java.util.Objects;

/**
 * 
 * @author Sandip Ram
 *
 */
public class CustomHashMap {

   private static final int SIZE = 16;
   private Entry table[] = new Entry[SIZE];

   class Entry {

      final String key;
      String value;
      Entry next;

      Entry(String k, String v) {
         key = k;
         value = v;
      }

      public String getValue() {
         return value;
      }

      public void setValue(String value) {
         this.value = value;
      }

      public String getKey() {
         return key;
      }
   }

   /**
   * Returns the entry mapped to key in the HashMap.
   */
   public Entry get(String k) {
      int hash = k.hashCode() % SIZE;
      Entry e = table[hash];
      // Bucket is identified by hashCode and traversed the bucket
      // till element is not found.
      while (Objects.nonNull(e)) {
         if (e.key.equals(k)) {
            return e;
         }
         e = e.next;
      }
      return null;
   }

   /**
   * If the map previously contained a mapping for the key, the old value is
   * replaced.
   */
   public void put(String k, String v) {
      int hash = k.hashCode() % SIZE;
      Entry e = table[hash];

      if (Objects.nonNull(e)) {
         if (e.key.equals(k)) {
            e.value = v;
         } else {
            while (e.next != null) {
               e = e.next;
            }
            Entry entryInOldBucket = new Entry(k, v);
            e.next = entryInOldBucket;
         }
      } else {
         Entry entryInNewBucket = new Entry(k, v);
         table[hash] = entryInNewBucket;
      }
   }

   public static void main(String[] args) {

      CustomHashMap customHashMap = new CustomHashMap();

      customHashMap.put("a", "a");
      customHashMap.put("b", "b");
      customHashMap.put("c", "c");
      customHashMap.put("d", "d");

      Entry entry = customHashMap.get("b");
      System.out.println("Value : " + entry.getValue());
   }
}


Answer is