Hash Table Implementation in Java Homework Answers Needed
Your Question:
Marked Exercises:
1. Consider the following table, create a Separate chaining Hash Table and Linear probing Hash table for the above table. Consider initial array size to be 8 elements long. Discuss what should be the ideal size of array for the above values and justify.
V 12 6
0 45 4
Z 23 2
2. Write a program in JAVA to see the hash code generated by JAVA for two integers 12 and 28, two doubles 34.55 and 45.67, and two strings of your own choice. Run the program and upload the outcome.
Step By Step Answers with Explanation
In Separate Chaining, we use an array where each element is a linked list. The hash code of the key determines which linked list to place the key-value pair. If two keys have the same hash code, they will be stored in the same linked list.
We'll use the modulo operator (%) to determine the index where each key-value pair should be stored based on its hash code.
public SeparateChainingHashTable(int initialSize) {
table = new LinkedList[initialSize];
}
// Hash function
// Insert a key-value pair into the hash table
public void put(String key, int value) {
// Get the value associated with a key
public int get(String key) {
}
}
String key;
int value;
}
}
private int[] values;
private int size;
values = new int[initialCapacity];
size = 0;
int hashCode = key.hashCode();
return hashCode % capacity;
while (keys[index] != null) {
if (keys[index].equals(key)) {
}
keys[index] = key;
public int get(String key) {
int index = hash(key);
index = (index + 1) % capacity; // Linear probing
}
java
public class Main {
// Inserting data into hash tables
separateChainingTable.put("B", 2);
separateChainingTable.put("P", 22);
separateChainingTable.put("R", 87);
linearProbingTable.put("F", 1);
linearProbingTable.put("S", 7);
linearProbingTable.put("M", 54);
linearProbingTable.put("Y", 2);
System.out.println("Value associated with key 'Z': " + separateChainingTable.get("Z"));
System.out.println("\nLinear Probing Table:");
Ideal Size of Array:
The ideal size of the array for a hash table depends on various factors, including the expected number of key-value pairs and the desired level of performance. The goal is to minimize collisions (i.e., situations where two keys hash to the same index) while keeping memory usage reasonable.