I understand the idea behind a hash table, but the implementation is getting frustrating. I have done some reading and gotten mixed answers. I have read that I could implement a generic array of objects as follows:
TableContainer[] classTable =
(TableContainer<Object,Object>[]) new TableContainer[256];
where tableContainer is:
class TableContainer<key,val>{
Object key = null;
Object val = null;
}
The problem I am having is that when I try to pass the following code in a function:
classTable[i].key = x
I get a null pointer exception. I understand creating generic arrays in java gets messy because of type erasure but I thought the above implementation would work. Is there any way to create a list or array of generics to be utilized as a hashtable? (no hashtable/hashmap classes permitted)
First of all you are creating an empty array:
and since you cannot resize arrays over time, it doesn’t have much sense. Providing that you actually create an array of some positive size, you must remember one thing: you created an array of references. And by default each array is initialized to default (zero) values, which happens to be
nullfor references.Thus you need something like this: