Reputation: 31
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
Upvotes: 1
Views: 76
Reputation: 41281
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.
Upvotes: 1