11package com .jwetherell .algorithms .data_structures ;
22
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
36
47/**
5- * Hash Map backed by an array of LinkedLists .
8+ * Hash Map backed by an array of ArrayLists .
69 *
710 * @author Justin Wetherell <phishman3579@gmail.com>
811 */
912public class HashMap {
1013
1114 private int hashingKey = 10 ;
12- private LinkedList [] map = null ;
15+ private List < Integer > [] map = null ;
1316 private int size = 0 ;
1417
1518 public HashMap () {
@@ -23,10 +26,11 @@ public HashMap(int[] values) {
2326 populate (values );
2427 }
2528
29+ @ SuppressWarnings ("unchecked" )
2630 private void initializeMap () {
27- map = new LinkedList [hashingKey ];
31+ map = new ArrayList [hashingKey ];
2832 for (int i =0 ; i <map .length ; i ++) {
29- map [i ] = new LinkedList ();
33+ map [i ] = new ArrayList < Integer > ();
3034 }
3135 }
3236
@@ -42,9 +46,9 @@ private int hashingFunction(int key) {
4246
4347 public boolean put (int key , int value ) {
4448 int hashedKey = hashingFunction (key );
45- LinkedList list = map [hashedKey ];
49+ List < Integer > list = map [hashedKey ];
4650 // Do not add duplicates
47- for (int i =0 ; i <list .getSize (); i ++) {
51+ for (int i =0 ; i <list .size (); i ++) {
4852 int v = list .get (i );
4953 if (v == value ) return false ;
5054 }
@@ -55,8 +59,8 @@ public boolean put(int key, int value) {
5559
5660 public boolean remove (int key ) {
5761 int hashedKey = hashingFunction (key );
58- LinkedList list = map [hashedKey ];
59- if (list .remove (key )) {
62+ List < Integer > list = map [hashedKey ];
63+ if (list .remove (( Object ) key )) {
6064 size --;
6165 return true ;
6266 }
@@ -65,8 +69,8 @@ public boolean remove(int key) {
6569
6670 public boolean contains (int value ) {
6771 for (int key =0 ; key <map .length ; key ++) {
68- LinkedList list = map [key ];
69- for (int item =0 ; item <list .getSize (); item ++) {
72+ List < Integer > list = map [key ];
73+ for (int item =0 ; item <list .size (); item ++) {
7074 int v = list .get (item );
7175 if (v == value ) return true ;
7276 }
@@ -81,8 +85,8 @@ public int getSize() {
8185 public String toString () {
8286 StringBuilder builder = new StringBuilder ();
8387 for (int key =0 ; key <map .length ; key ++) {
84- LinkedList list = map [key ];
85- for (int item =0 ; item <list .getSize (); item ++) {
88+ List < Integer > list = map [key ];
89+ for (int item =0 ; item <list .size (); item ++) {
8690 int value = list .get (item );
8791 if (value !=Integer .MIN_VALUE ) builder .append (key ).append ("=" ).append (value ).append (", " );
8892 }
0 commit comments