I'm trying to implement a hashtable using chaining and without any libraries (other than those already in my code), but I'm very stuck. For some reason, the data (100 lines of ints) isn't being added to the list, as seen when it's printed, except for one in the second position (which I assume I need a toString() method for.) Is there any tips or solutions I could get as to how to make this work?
Thanks in advance!
Main + array declaration:
static LinkedList<Node> hashTable[] = new LinkedList[100];
static class Node {
int value;
int key;
}
public static void main(String[] args) throws FileNotFoundException {
File f = new File("Ex5.txt");
Scanner scan = new Scanner(f);
if (f.exists() == false) {
System.out.println("File doesn't exist or could not be found.");
System.exit(0);
}
while (scan.hasNextInt()) {
int n = scan.nextInt();
insert(1, hashFunction(n));
}
for (int i = 0; i < 100; ++i) {
System.out.println(hashTable[i]);
}
}
Insert Function:
public static void insert(int key, int value) {
int index = key % 100;
LinkedList<Node> items = hashTable[index];
if (items == null) {
items = new LinkedList<>();
Node item = new Node();
item.key = key;
item.value = value;
items.add(item);
hashTable[index] = items;
} else {
for (Node item : items) {
if (item.key == key) {
item.value = value;
return;
}
}
Node item = new Node();
item.key = key;
item.value = value;
items.add(item);
}
}
Hashing function:
public static int hashFunction(int value) {
int hashKey = value % 100;
return hashKey;
}
You shall make two changes:
You shall use hashfunction to get the key and keep value as is.
Remove index=key%100 from insert, instead use passed key for traversing.
Hope this helps.
-------------------------- EDIT --------------------
For printing actual values in linked list, please override toString() method in your Node Class and return a string representation of Key-Value.