Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA: Write a remove, rehash and size methods for HashTableChain Class: import j

ID: 3817095 • Letter: J

Question

JAVA: Write a remove, rehash and size methods for HashTableChain Class:

import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;

public class HashtableChain<K, V> implements KWHashMap<K, V>
{
private LinkedList<Entry<K, V>>[] table;
private int numKeys;
private static final int CAPACITY = 101;
private static final double LOAD_THRESHOLD = 3.0;

private static class Entry<K, V> implements Map.Entry<K, V>
{
private K key;
private V value;

public Entry(K key, V value)
{
this.key = key;
this.value = value;
}

@Override
public K getKey(){
return key;
}

@Override
public V getValue() {
return value;
}

@Override
public V setValue(V val) {
V oldVal = value;
value = val;
return oldVal;
}

}

public HashtableChain() {
table = new LinkedList[CAPACITY];
}
  

@Override
public V get(Object key) {
int index = key.hashCode() % table.length;
if (index < 0) {
index += table.length;
}
if (table[index] == null) {
return null; // key is not in the table.
}
// Search the list at table[index] to find the key.
for (Entry<K, V> nextItem : table[index]) {
if (nextItem.key.equals(key)) {
return nextItem.value;
}
}

// assert: key is not in the table.
return null;
}

@Override
public V put(K key, V value) {
int index = key.hashCode() % table.length;
if (index < 0) {
index += table.length;
}
if (table[index] == null) {
// Create a new linked list at table[index].
table[index] = new LinkedList<Entry<K, V>>();
}

// Search the list at table[index] to find the key.
for (Entry<K, V> nextItem : table[index]) {
// If the search is successful, replace the old value.
if (nextItem.key.equals(key)) {
// Replace value for this key.
V oldVal = nextItem.value;
nextItem.setValue(value);
return oldVal;
}
}

// assert: key is not in the table, add new item.
table[index].addFirst(new Entry<K, V>(key, value));
numKeys++;
if (numKeys > (LOAD_THRESHOLD * table.length)) {
// rehash();
}
return null;
}

public boolean isEmpty() {
return numKeys == 0;
}
  
public int size(){
       return table.length;
}
  

}

Explanation / Answer

For all of theis we have to import

import java.util.Hashtable;

import java.util.Set;

import java.util.Map.Entry;

Remove:

To remove the hash table we will use clear method

By creating object to the given class

and we will remove

ex:

Hashtable<String, String> hm = new HashtableChain<String, String>();

hm.clear();

Rehash:

By using the rehash() methos we will rehash the hashtable chain

ex:

Hashtable<String, String> hm = new HashtableChain<String, String>();

hm.rehash();

Size:

to get the size we will use size methos pre-defined

ex:

Hashtable<String, String> hm = new HashtableChain<String, String>();

hm.size();