From df34c3fdd14d6abeb0208202e0ed114cfbf91fae Mon Sep 17 00:00:00 2001 From: ParitoshAggarwal Date: Sun, 6 Aug 2017 19:46:08 +0530 Subject: [PATCH] Add files via upload HashMap implemented Code is working and checked twice to avoid any errors --- data_structures/HashMap/HashMap.java | 141 +++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 data_structures/HashMap/HashMap.java diff --git a/data_structures/HashMap/HashMap.java b/data_structures/HashMap/HashMap.java new file mode 100644 index 000000000..50856d523 --- /dev/null +++ b/data_structures/HashMap/HashMap.java @@ -0,0 +1,141 @@ +package hashmap; + +import java.util.ArrayList; +import java.util.LinkedList; + +public class HashMap { + public class hmnodes{ //HashMap nodes + K key; + V value; + } + + private int size=0; //size of hashmap + private LinkedList buckets[]; //array of addresses of list + + public HashMap(){ + buckets=new LinkedList[4]; //initially create bucket of any size + for(int i=0;i<4;i++) + buckets[i]=new LinkedList<>(); + } + + public void put(K key,V value) throws Exception{ + int bi=bucketIndex(key); //find the index,the new key will be inserted in linklist at that index + int fountAt=find(bi,key); //check if key already exists or not + if(fountAt==-1){ + hmnodes temp=new hmnodes(); //if doesn't exist create new node and insert + temp.key=key; + temp.value=value; + buckets[bi].addLast(temp); + this.size++; + }else{ + buckets[bi].get(fountAt).value=value;//if already exist modify the value + } + + double lambda = (this.size*1.0)/this.buckets.length; + if(lambda>2.0){ + rehash(); //rehashing function which will increase the size of bucket as soon as lambda exceeds 2.0 + } + + return; + } + + + public V get(K key) throws Exception{ + int bi=bucketIndex(key); + int fountAt=find(bi,key); + if(fountAt==-1){ + return null; + }else{ + return buckets[bi].get(fountAt).value; + } + } + + public V remove(K key) throws Exception{ + int bi=bucketIndex(key); + int fountAt=find(bi,key); + if(fountAt==-1){ + return null; + }else{ + this.size--; + return buckets[bi].remove(fountAt).value; + } + } + + public boolean containskey(K key) throws Exception{ + int bi=bucketIndex(key); + int fountAt=find(bi,key); + if(fountAt==-1){ + return false; + }else{ + return true; + } + } + + public int size(){ + return this.size; + } + + + public boolean isempty(){ + return this.size==0; + } + + public ArrayList keyset() throws Exception{ + ArrayList arr=new ArrayList<>(); + for(int i=0;i valueset() throws Exception{ + ArrayList arr=new ArrayList<>(); + for(int i=0;i"+temp.value+"]"); + } + System.out.println(); + } + } + + public int find(int bi,K key) throws Exception{ + for(int i=0;i ob[]= buckets; + buckets=new LinkedList[ob.length*2]; + for(int i=0;i(); + + size = 0; + for(int i=0;i