我有一个简单的类,构造函数创建一个对象数组,并获取数组中每个对象的哈希码,如下所示。在运行时,程序在调用System.identityHashCode(Object x)时抛出空指针异常。我已经实例化了Object。为什么会发生异常?
public class ArrayOfObjects
{
private Object[] array;
private int[] arrayIdentity;
public ArrayOfObjects(int N)
{
array = new Object[N];
for (int i = 0; i < N; i ++)
{
array[i] = new Object();
**// The line below throws null pointer exception.**
arrayIdentity[i] = System.identityHashCode(array[i]);
}
}
public static void main(String[] args)
{
ArrayOfObjects arrayOfObjects = new ArrayOfObjects(10);
// Do something.
}
}
答案 0 :(得分:0)
您还需要实例化arrayIdentity
:
array = new Object[N];
arrayIdentity = new int[N];