-3

This is a code to implement the hashing without using the java hash function. I got an error java.lang.NullPointerException though

A class to create a contact with phone and name:

public class Contact {
  String name;
  int phone;
}

public class Hash {
  public static void main(String[] args) {

    Contact[] table = new Contact[1009];

    int tableSize = 1009;

    int out = calcHash("Ahmed", tableSize);

    table[out].name = "Ahmed";    //This line has an error
    table[out].phone = 23445677;  //This line has an error

    System.out.println(out);

  }

A method to generate a hash value for the name:

  public static int calcHash(String key, int tableSize) {


    int i, l = key.length();
    int hash = 0;
    for (i = 0; i < l; i++) {

      hash += Character.getNumericValue(key.charAt(i));
      hash += hash << 10;
      hash ^= hash >> 6;
    }
    hash += hash << 3;
    hash ^= hash >> 11;
    hash += hash << 15;
    if (hash > 0) return hash % tableSize;
    else return -hash % tableSize;
  }
}

These lines in the Hash class are throwing exceptions:

table[out].name = "Ahmed";    //This line has an error
table[out].phone = 23445677;  //This line has an error
Nissa
  • 4,636
  • 8
  • 29
  • 37
y.eska
  • 67
  • 6

1 Answers1

0

table[Out] is null when the following line is executed:

table[Out].Name = "Ahmed";  

Try setting table[Out] to a new instance before setting the properties:

table[Out] = new contact();
table[Out].Name = "Ahmed";    
table[Out].phone = 23445677;  
gannaway
  • 1,872
  • 12
  • 14