Java 在声明对象并为数组分配索引后,我得到一个空错误
这是在不使用java哈希函数的情况下实现哈希的代码。 但是我得到了一个错误Java 在声明对象并为数组分配索引后,我得到一个空错误,java,nullpointerexception,Java,Nullpointerexception,这是在不使用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];
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;
}
}
执行以下行时,
表[Out]
为空:
table[Out].Name = "Ahmed";
在设置属性之前,请尝试将表[Out]设置为新实例:
table[Out] = new contact();
table[Out].Name = "Ahmed";
table[Out].phone = 23445677;
非常感谢你!
table[Out] = new contact();
table[Out].Name = "Ahmed";
table[Out].phone = 23445677;