HashMap implementation

How to implement the hashmap without using HashMap class from java collection util package.

This is one of the interview question asked from JP Morgan

I haven't answer in the following way but i have tried to explain in Datastructure. It would help someone like me .. :) enjoy

this can be enhance in more but to make it simple ..

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 *
 */
/**
 * @author PraveenKumar
 *
 */
public class HashMapDS {
 /**
  * @param args
  */

 public static void main(String[] args) {
 
  HashMap map=new HashMap();
  for(int i=0;i<15 br="" i="">   map.put("a"+i, i+10);
  }
  System.out.println(""+map.get("a1")+25);
  map.display(map);
 }

}



import java.util.ArrayList;
import java.util.List;
/**
 *
 */
/**
 * @author PraveenKumar
 *
 */
public class HashMap {
 static Object [][] a=null;
 static ArrayList hashMap=new ArrayList<>();

 /**
  *
  * @param hashMap2
  */
 public void display(ArrayList hashMap2) {
  Object [][] temp=new Object[1][2];
  for(int i=0;i   temp=(Object[][]) hashMap2.get(i);
   System.out.println(temp[0][0]+":"+temp[0][1]);
  }
 }
/**
 * Add the key value pair into map object
 *
 * @param key
 * @param value
 */
 public void put(Object key, Object value) {
  a=new Object[1][2];

  a[0][0]= key;
  a[0][1]= value;
  hashMap.add(a);

 }
 /**
  * Display all the key and values in the  map object
  * @param map
  */
 public void display(HashMap map){
  display(map.hashMap);
 }
 /**
  * get all the keys from the map object
  * @param hashMap2
  * @return
  */
 public List getKeys(ArrayList hashMap2) {
  List mapKeys =new ArrayList();
  Object [][] temp=new Object[1][2];
  for(int i=0;i   temp=(Object[][]) hashMap2.get(i);
   mapKeys.add(temp[0][0]);
   //System.out.println(temp[0][0]+":"+temp[0][1]);
  }
  return mapKeys;
 }

 /**
  * return the value of key from the map
  * @param key
  * @return
  */
 public Object get(Object key) {
  Object value=new Object();
  Object [][] temp=new Object[1][2];
  for(int i=0;i   temp=(Object[][]) hashMap.get(i);
   if(key.equals(temp[0][0]))
    value=temp[0][1];
  }
  return value;
 }

}

Comments

Popular posts from this blog

Spring MVC with Sqlite sample

Struts Tutorial Page