简体   繁体   中英

NullPointer Exception java arrays

I know this is usually because something hasn't been initialised, but I've checked and I'm sure everything's been initialised! I've looked at loads of examples to check how to initialise arrays of objects. Exact error:

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)

So I think that's pointing to my copyArray method, and the lines where I've used it, so here are those bits of code:

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;
}

And another section that uses the copyArray method:

    GravField[] gravityObject = {earthGravField, sunGravField};
    PhysicsVector[] position = {newPos, sunNewPos}; 
    PhysicsVector[] velocity = {newV, sunNewV};
    PhysicsVector[] gravField = {earthGrav, sunGrav};
    double[] planetMass = {earthMass, sunMass};
    Particle[] planets = {earth, sun};

    PhysicsVector[] newP= new PhysicsVector[position.length];

    PhysicsVector[] newGrav = new PhysicsVector[gravField.length];

    PhysicsVector[] newVel = new PhysicsVector[velocity.length];

    PhysicsVector sum1 = new PhysicsVector(0,0);
    PhysicsVector sum2= new PhysicsVector(0,0);
    PhysicsVector sum3= new PhysicsVector(0,0);

    do{
        PhysicsVector[] y = new PhysicsVector[gravField.length];
        y=copyArray(gravField);                        //This is line 117, pointed to in error message
        PhysicsVector[] z = new PhysicsVector[gravField.length];
        z=copyArray(gravField);

You pass array elements and not the array to System.arraycopy . The NullPointerException is because copy[i] is null.

The right way is to pass the arrays, no need to loop over the elements:

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

In case you want a shallow copy of an array it is even easier:

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

You don't need to have the Sytsem.arraycopy call in a for loop. Just call it once and the entirety of the source array will be copied to the target array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM