// -- Creates a K-V pair. Key must be a string, Value is an object. Returns false if HashMap // already full. boolean set(String key, Object value) { int index = Math.abs(key.hashCode() % this.MY_SIZE); /* First, check if key exists in the appropriate bucket. If it does, overwrite value. If not, then create new K-V pair in array. */ if (this.table[index] == null) { if (this.NUM_ELEMENTS == this.MY_SIZE) { // Check if HashMap full. If full, print to console, and return false. System.out.println("ERROR: Trying to insert element in full CustomHashMap"); return false; } KVPairNode temp = new KVPairNode(key, value); this.table[index] = temp; this.NUM_ELEMENTS++; return true; } else { KVPairNode start; start = this.table[index]; while (start != null) { if (start.theKey.equals(key)) { // Overwrite value. Don't increment NUM_ELEMENTS start.theValue = value; return true; } start = start.next; } if (this.NUM_ELEMENTS == this.MY_SIZE) { // Check if HashMap full. If full, print to console, and return false. System.out.println("ERROR: Trying to insert element in full CustomHashMap"); return false; } KVPairNode temp = new KVPairNode(key, value); temp.next = this.table[index]; this.table[index] = temp; this.NUM_ELEMENTS++; return true; } }
// -- Deletes a K-V Pair from HashMap, returns the value deleted. Returns null and deletes nothing // if key does not exist. public Object delete(String key) { KVPairNode theNode = this.getNode(key); Object output; /* We want to "delete" this node. If the next node is null, just make this current node null. Else, copy the next Node's information into the current node. */ if (theNode != null) { output = theNode.theValue; if (theNode.next == null) { theNode = null; } else { theNode.theKey = theNode.next.theKey; theNode.theValue = theNode.next.theValue; theNode.next = theNode.next.next; } this.NUM_ELEMENTS--; return output; } else { System.out.println("ERROR: Key does not exist."); return null; } }