I've tried to implement a hash table myself without data structures provided by JDK. (such as Linkedlist...)
So I tried to implement a hash table by implementing an array of linked lists. However, it returns NullPointerExcetion
.
This is main code.
public static void main(String[] args) {
HTable test = new HTable(500000);
for(int i = 0; i < 50000; i++) {
BigInteger s = BigInteger.ONE;
for(int j = 0; j <= 0; j++) {
s = s.multiply(BigInteger.valueOf(37));
}
if(test.insert(s, String.valueOf(s))) {}
}
}
and HTable is below.
class HTable {
static int length;
Linkedlist[] HT;
HTable(int size) {
...
Linkedlist[] HT = new Linkedlist[sample];
for(int j = 0; j < sample; j++) {
HT[j] = new Linkedlist();
}
length = sample;
}
public boolean insert(BigInteger i, String s) {
int sum = 0;
String[] i_toString = (i.toString()).split("");
System.out.println(i_toString[0]);
int[] data = new int[i_toString.length];
int[] multiple = new int[i_toString.length];
data[0] = Integer.parseInt(i_toString[0]);
multiple[0] = (int) Math.pow(data[0], (int)Math.log10(length));
...
int index = sum % length;
if(HT[index].isEmpty()) {
HT[index].insertAtFront(i, s);
return true;
}
for(Iterator v = HT[index].getIterator(); !v.atEnd(); v.next()) {
if(v.getdata() == i) {
return false;
}
}
HT[index].insertAtFront(i, s);
return true;
}
and finally, this is Linkedlist code.
class Linkedlist {
public Node first;
public Linkedlist() {
first = null;
}
public boolean isEmpty() {
return (first == null);
}
public void insertAtFront(BigInteger x, String y) {
Node newnode = new Node();
newnode.data = x;
newnode.payload = y;
newnode.next = first;
first.prev = newnode;
first = newnode;
}
I have been struggling to identify the problem, but I could not find a clear solution. However, I found that in inner constructor, HF[index] can be used, but in HTable.insert can't.
Why is that?