空指针异常java数组

空指针异常java数组,java,Java,我知道这通常是因为有些东西还没有初始化,但我已经检查过了,我确信所有东西都已初始化!我看了大量的例子来检查如何初始化对象数组。确切错误: Exception in thread "main" java.lang.NullPointerException at java.lang.System.arraycopy(Native Method) at SolarSim.copyArray(solarSim.java:17) at SolarSim.main(Solarsim.java:117)

我知道这通常是因为有些东西还没有初始化,但我已经检查过了,我确信所有东西都已初始化!我看了大量的例子来检查如何初始化对象数组。确切错误:

Exception in thread "main" java.lang.NullPointerException

at java.lang.System.arraycopy(Native Method)

at SolarSim.copyArray(solarSim.java:17)

at SolarSim.main(Solarsim.java:117)
我想这是指向我的copyArray方法,以及我使用它的行,下面是这些代码:

public static PhysicsVector[] copyArray(PhysicsVector[] a) {
    int length = a.length;
    PhysicsVector[] copy = new PhysicsVector[length];
    for (int i = 0; i < length; i++) {
        System.arraycopy(a[i], 0, copy[i], 0, length);
    }
    return copy;
}

您不需要在for循环中调用Sytsem.arraycopy。只需调用它一次,源数组的整个内容就会被复制到目标数组。

您不需要在for循环中调用Sytsem.arraycopy。只需调用一次,源数组的全部内容就会被复制到目标数组。

您将数组元素而不是数组传递到
System.arraycopy
。NullPointerException是因为
copy[i]
为null

正确的方法是传递数组,无需在元素上循环:

public static PhysicsVector[] copyArray(PhysicsVector[] a) {
    int length = a.length;
    PhysicsVector[] copy = new PhysicsVector[length];
    System.arraycopy(a, 0, copy, 0, length);
    return copy;
}
如果需要阵列的浅拷贝,则更容易:

public static PhysicsVector[] copyArray(PhysicsVector[] a) {
    return a.clone();
}

将数组元素而不是数组传递给
System.arraycopy
。NullPointerException是因为
copy[i]
为null

正确的方法是传递数组,无需在元素上循环:

public static PhysicsVector[] copyArray(PhysicsVector[] a) {
    int length = a.length;
    PhysicsVector[] copy = new PhysicsVector[length];
    System.arraycopy(a, 0, copy, 0, length);
    return copy;
}
如果需要阵列的浅拷贝,则更容易:

public static PhysicsVector[] copyArray(PhysicsVector[] a) {
    return a.clone();
}

我有点惊讶
System.arraycopy(PhysicsVector,int,PhysicsVector,int,int)甚至可以工作,我觉得它需要数组。同样,这也可能是您出错的原因可能重复的I可能是错误的,但不是
System.arraycopy(a[I],0,copy[I],0,length)
应该这样使用
System.arraycopy(a,i,copy,i,length)?@phflack也必须修复,谢谢。@showp1984应该是这样的。我也得把它修好,否则就不行了!我有点惊讶
System.arraycopy(PhysicsVector,int,PhysicsVector,int,int)甚至可以工作,我觉得它需要数组。同样,这也可能是您出错的原因可能重复的I可能是错误的,但不是
System.arraycopy(a[I],0,copy[I],0,length)
应该这样使用
System.arraycopy(a,i,copy,i,length)?@phflack也必须修复,谢谢。@showp1984应该是这样的。我也得把它修好,否则就不行了!