这是在不使用java哈希函数的情况下实现散列的代码。
我收到了错误java.lang.NullPointerException
用于创建与电话和姓名联系的班级:
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);
}
为名称生成哈希值的方法:
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;
}
}
Hash
类中的这些行抛出异常:
table[out].name = "Ahmed"; //This line has an error
table[out].phone = 23445677; //This line has an error
答案 0 :(得分:0)
table[Out]
为空:
table[Out].Name = "Ahmed";
在设置属性之前,尝试将table[Out]
设置为新实例:
table[Out] = new contact();
table[Out].Name = "Ahmed";
table[Out].phone = 23445677;