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

Use Java to Create a hash table class/struct. Define an array that holds 27 elem

ID: 3812065 • Letter: U

Question

Use Java to Create a hash table class/struct.

Define an array that holds 27 elements.

Define a function called Hash(int)

-This function returns the modulo of that int by the size of the table (array).

Define an add function that takes an integer.

-This function takes the integer, determines the hash of that number by calling the above hash function, then adds it to the table using linear probing for collision resolution.

Define a function that looks up a value, it takes an integer, return -1 if the value is not in the table.

Create a main that allows the user to add and lookup items in the table.

Explanation / Answer

public class Node {
private int key;
private int value;

Node(int key, int value) {
this.key = key;
this.value = value;
}   

public int getKey() {
return key;
}

public int getValue() {
return value;
}
}

public class HashTable {
private final static int TABLE_SIZE = 128;

Node[] table;

HashTable() {
table = new Node[TABLE_SIZE];
for (int i = 0; i < TABLE_SIZE; i++)
table[i] = null;
}

public int get(int key) {
int hash = (key % TABLE_SIZE);
while (table[hash] != null && table[hash].getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
if (table[hash] == null)
return -1;
else
return table[hash].getValue();
}

public void put(int key, int value) {
int hash = (key % TABLE_SIZE);
while (table[hash] != null && table[hash].getKey() != key)
hash = (hash + 1) % TABLE_SIZE;
table[hash] = new Node(key, value);
}
}

public class Main {
   public static void main(String[] argv){
       HashTable table = new HashTable();
       table.put(1, 1);
       table.put(2, 2);
       table.put(3, 3);
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote