Google Interview Question
Software Engineer / DevelopersCountry: United States
Please find the Implementation
public class CustomHashMap {
private LinkedHashEntry[] hashTable;
private static final int HASH_LENGTH = 100;
public CustomHashMap(){
hashTable = new LinkedHashEntry[HASH_LENGTH];
}
public void put(Object key,Object value){
LinkedHashEntry node = getNode(key);
if(node == null){
hashTable[getHashCode(key)]=new LinkedHashEntry(key, value);
return;
}
while(node.hasNext() && !(node.getKey().equals(key)))
node=node.next;
//updation
if(key.equals(node.getKey()))
node.value=value;
System.out.println(" Node "+node.getKey()+" "+ node.value+ " "+node.next);
//addition
LinkedHashEntry newEntry = new LinkedHashEntry(key, value);
node.next=newEntry;
System.out.println(" Node "+node.getKey()+" "+ node.value+ " "+node.next);
System.out.println(" newEntry "+newEntry.getKey()+" "+ newEntry.value+ " "+newEntry.next);
System.out.println(newEntry);
}
public Object get(Object key){
if(key == null)
return null;
LinkedHashEntry node = getNode(key);
if(node == null)
return null;
while(node.hasNext() && !key.equals(node.getKey()))
node=node.next;
if(key.equals(node.getKey()))
return node.value;
return null;
}
public Boolean remove(Object key){
if(key == null)
return false;
LinkedHashEntry node = getNode(key);
LinkedHashEntry previousNode=node;
while(node.hasNext() && !key.equals(node.getKey())){
previousNode=node;
node=node.next;
}
if(key.equals(node.getKey())){
previousNode.next=node.next;
node.next=null;
return true;
}
return false;
}
private LinkedHashEntry getNode(Object key) {
System.out.println("getHashCode(key) "+ getHashCode(key));
return hashTable[getHashCode(key)];
}
private int getHashCode(Object key) {
return (key.hashCode() % HASH_LENGTH);
}
private class LinkedHashEntry{
private Object key;
private Object value;
private LinkedHashEntry next;
LinkedHashEntry(Object key,Object value){
this.key=key;
this.value=value;
this.next=null;
}
Object getKey(){
return key;
}
Boolean hasNext(){
return (next != null);
}
}
public static void main(String ... s){
CustomHashMap customHashMap = new CustomHashMap();
customHashMap.put("hi","hi");
customHashMap.put(29,"hi bye");
}
}
Read the question properly. I want the hash function implement that can handle any type of data(say String, Integer, Object etc) , hash it and the result should be the index of the hashArray.
Implement two-level of hashing, two hash functions
- confused_banda November 18, 2013h1( typename ) returns a key k1 in table T1 which contains links to a separate table T2(one T2 per entry of T1)
h2(k1, object) returns a key k2 (links to entry within T2)
To hash h2( object.class, object ), first hash gives a key to location of object in an entire arrangement of two hash tables.