I am implementing Hash Table through java. When I implement the following code, I get a NullPointer Exception error but if I replace the else statement in void put(int key, int value) in class HashTable with the statement kv[key]=new KeyValue(key,value); It works! Can someone explain why is this happening? Please help!
public class KeyValue {
int key;
int value;
KeyValue(int k, int v)
{
key = k;
value = v;
}
public int getKey(){
return key;
}
public int getValue()
{
return value;
}
public void put(int k, int v)
{
key = k;
value = v;
}
}
public class HashTable{
KeyValue[] kv;
HashTable(){
kv = new KeyValue[4];
for (int i=0; i<4 ; i++)
{ kv[i]=null;
}
}
void put(int key, int value)
{
if((kv[key]!=null) || (key<0 && key>=4))
{
;
}
else
{
kv[key].put(key,value);
}
}
int get(int key)
{
int value;
value=kv[key].getValue();
return value;
}
public static void main(String[] a){
HashTable h = new HashTable();
h.put(1,2);
System.out.println(h.get(1));
}
}