11package DataStructures .HashMap .Hashing ;
22
3+ import java .util .*;
4+
35/**
46 * This class is an implementation of a hash table using linear probing
5- *
7+ * It uses a dynamic array to lengthen the size of the hash table when
8+ * load factor > .7
69 */
710public class HashMapLinearProbing {
8- private int hsize ;
9- private Integer [] buckets ;
11+ private int hsize ; //size of the hash table
12+ private Integer [] buckets ; //array representing the table
1013 private Integer AVAILABLE ;
14+ private int size ; //amount of elements in the hash table
1115
1216 /**
1317 * Constructor initializes buckets array, hsize, and creates dummy object for AVAILABLE
1418 * @param hsize the desired size of the hash map
1519 */
1620 public HashMapLinearProbing (int hsize ) {
17- buckets = new Integer [hsize ];
21+ this . buckets = new Integer [hsize ];
1822 this .hsize = hsize ;
19- AVAILABLE = new Integer (Integer .MIN_VALUE );
23+ this .AVAILABLE = new Integer (Integer .MIN_VALUE );
24+ this .size = 0 ;
2025 }
2126
2227 /**
@@ -48,6 +53,7 @@ public void insertHash(int key) {
4853 for (int i = 0 ;i < hsize ; i ++) {
4954 if (buckets [hash ] == null || buckets [hash ] == AVAILABLE ) {
5055 buckets [hash ] = wrappedInt ;
56+ size ++;
5157 return ;
5258 }
5359
@@ -56,7 +62,7 @@ public void insertHash(int key) {
5662 } else {
5763 hash = 0 ;
5864 }
59- }
65+ }
6066 }
6167
6268 /**
@@ -75,6 +81,7 @@ public void deleteHash(int key) {
7581 for (int i = 0 ;i < hsize ; i ++) {
7682 if (buckets [hash ] != null && buckets [hash ].equals (wrappedInt )) {
7783 buckets [hash ] = AVAILABLE ;
84+ size --;
7885 return ;
7986 }
8087
@@ -116,10 +123,12 @@ public int findHash(int key) {
116123 }
117124
118125 for (int i = 0 ;i < hsize ; i ++) {
119- if (buckets [hash ].equals (wrappedInt )) {
120- buckets [hash ] = AVAILABLE ;
121- return hash ;
122- }
126+ try {
127+ if (buckets [hash ].equals (wrappedInt )) {
128+ buckets [hash ] = AVAILABLE ;
129+ return hash ;
130+ }
131+ } catch (Exception E ) {}
123132
124133 if (hash + 1 < hsize ) {
125134 hash ++;
@@ -131,6 +140,27 @@ public int findHash(int key) {
131140 return -1 ;
132141 }
133142
143+ private void lengthenTable () {
144+ buckets = Arrays .copyOf (buckets , hsize * 2 );
145+ hsize *= 2 ;
146+ System .out .println ("Table size is now: " + hsize );
147+ }
148+
149+ /**
150+ * Checks the load factor of the hash table
151+ * if greater than .7, automatically lengthens table
152+ * to prevent further collisions
153+ */
154+ public void checkLoadFactor () {
155+ double factor = (double ) size / hsize ;
156+ if (factor > .7 ) {
157+ System .out .println ("Load factor is " + factor + ", lengthening table" );
158+ lengthenTable ();
159+ } else {
160+ System .out .println ("Load factor is " + factor );
161+ }
162+ }
163+
134164 /**
135165 * isFull returns true if the hash map is full and false if not full
136166 * @return boolean is Empty
0 commit comments