I am trying to initialize a vector which has integers 1 to n in the form of strings for starters.
This is my declaration for the vector.
Vector<String> candidatesSet,frequentItemSet,mFCandidatesSet,mFSet = new <String>Vector();
The loop i using to initialize is
for(int i=0; i<crows; i++)
{
candidatesSet.add(Integer.toString(i+1));
}
Here we get the value of variable crowsduring runtime.
but it is throwing a NullpointerException in the line where i am adding strings to the objects.
I tried intializing the vector to a null by
candidatesSet = null;
But it didnt work
First of all, something like is wrong:
The correct syntax is this:
Second of all, if you do something like this:
…only
set5will be initialized. Each variable must be initialized independently. You could do something like this:…but then all of the variables would point to the same
Vector, and modifications to one variable would affect all the others. You’ll have to initialize each variable separately.Third, doing this:
…does nothing if
candidatesSetis not initialized yet, since non-primitive instance variables are initialized to null anyway. That’s your problem, you’re calling.add(String)on a null object, which cases aNullPointerException.Fixing those issues will make your code work, but there’s one last problem.
Vectoris a somewhat outdated class, and it has been replaced by the Java Collections API. Try usingArrayListinstead ofVector, like so:This will make your code more efficient and less archaic.