I cannot seem to find the correct way to write an array of a class. In this form no errors are thrown on compiling, but I receive an error when I try to make use of the array / class. The array of classes is in a class named HashTable (I’m required to write my own for an assignment) and I am testing it with the code below:
theHashTable.insert("aa", "ab");
Here is the HashTable class:
Edit: As pointed out by Aniket, fileNames was not being initialized. I corrected this below but receive the same error.
private class HashTable {
private class Value {
ArrayList<String> fileNames;
String word;
Value() {
fileNames = new ArrayList<String>();
}
}
private int currentSize = 101;
private Value[] items;
private HashTable() {
items = new Value[currentSize];
for (int i = 0; i < currentSize; i++) items[i] = new Value();
}
private int hash(String in) {
int out = 0;
for (int i = 0; i < in.length(); i++) out += 37*out+in.charAt(i);
out %= currentSize;
if (out < 0) out += currentSize;
return out;
}
public void insert(String inW, String inF) {
int index = hash(inW);
index = 0;
if (items[index].word.length() == 0) {
items[index].word = inW;
items[index].fileNames.add(inF);
}
else if (items[index].word.compareTo(inW) == 0) items[index].fileNames.add(inF);
else System.out.println("Collision");
}
}
fileNamesArrayList in yourValuesclass is never initialized. Write a constructor forValuesand InitializefileNames.