1

Why this didn't work

import java.util.ArrayList;
public class Vector 
{
    ArrayList<Long> vector;
    public Vector(long ...vector)
    {
        for (long value : vector)
            this.vector.add(new Long(value));
    }
}

when I make a new objet like Vector a = new Vector(4,7,8); it says

java.lang.NullPointerException

I've tried Arrays.asList(array); and

for (int i=0;i<vector.lenght;i++)
    this.vector.add(vector[i])

and same error

1 Answer 1

1

Your code is almost correct, in that the code to copy to an arraylist is properly written. However, the fact that the error is a NullPointerException clues us into knowing that something is null where it shouldn't be. In this case, vector itself is null, since it never got assigned a value. You can either declare vector and assign it using ArrayList<Long> vector = new ArrayList<>();, or assign vector = new ArrayList<>(); in the constructor.

Note: The <> diamond shorthand is a shorthand for generic types available in Java 7 and higher. If targeting Java 6, use new ArrayList<Long>(); on the right-hand-side.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.