Create Own HashMap
package com.userpakage.collection;
public class DesignOwnHashMap <E,V>{
private static final int MAX_LENGTH = 20;
// it is an array of Entry Class type,same as String[] str=new String[10];
Entry[] entryList = new Entry[MAX_LENGTH];
public static void main(String[] args) {
DesignOwnHashMap<Integer,String> dohm=new DesignOwnHashMap<Integer,String>(); dohm.put("1","Damodar");
dohm.put("3","Ravi"); dohm.put("9","Kavita"); dohm.put("9","Chandan"); Entry e=dohm.get("8");
if(e!=null){
if(e!=null){
System.out.println("key:"+e.getKey()+" and value:"+e.getValue());
}else{
System.out.println("No value store for given key");
}
}
private void put(String key, String value) {int hash=key.hashCode()%MAX_LENGTH;
//check whether any entry exist in entryList for the hash key or not //will return entry<key,value> from index location of the entryList array. Entry e=entryList[hash];
if(e!=null){if(e.getKey().equals(key)){
//over write the existing value if key matchede.setValue(value);
}else{
while(e.nextEntry!=null){ Entry entry=e.nextEntry; e=entry;
}
e.nextEntry=new Entry(key,value);
}
}else{
entryList[hash]=new Entry(key,value);
}
}
private Entry get(String key) {
int hash=key.hashCode()%MAX_LENGTH; Entry e=entryList[hash]; if(e!=null){
if(e.getKey().equals(key)){return e;
}else{
while(e!=null){
Entry entry=e.nextEntry;if(entry.getKey().equals(key)){
return entry;
}
}
}
}else{
return null;
}
}
package com.userpakage.collection;public class Entry {
private String key;private String value;
//will store the next entry in same bucket bucketEntry nextEntry=null;
public Entry(String key, String value) {this.key = key;
this.value = value;
}
public void setValue(String value) {this.value = value;
}
public String getKey() {return key;
}
public String getValue() {return value;
}
}