Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerexception being throwing when adding value into a vector

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

like image 297
StrawhatLuffy Avatar asked Mar 08 '26 01:03

StrawhatLuffy


2 Answers

First of all, something like is wrong:

Vector<String> set = new <String>Vector();

The correct syntax is this:

Vector<String> set = new Vector<String>();

Second of all, if you do something like this:

Vector<String> set1,set2,set3,set4,set5 = new Vector<String>();

...only set5 will be initialized. Each variable must be initialized independently. You could do something like this:

Vector<String> set1,set2,set3,set4,set5;
set1 = set2 = set3 = set4 = set5 = new Vector<String>();

...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:

candidatesSet = null;

...does nothing if candidatesSet is 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 a NullPointerException.

Fixing those issues will make your code work, but there's one last problem. Vector is a somewhat outdated class, and it has been replaced by the Java Collections API. Try using ArrayList instead of Vector, like so:

List<String> candidatesSet = new ArrayList<String>();

This will make your code more efficient and less archaic.

like image 51
Alexis King Avatar answered Mar 10 '26 14:03

Alexis King


try with

Vector<String> candidatesSet = new Vector<String>();

Before add an element

like image 29
OscarSan Avatar answered Mar 10 '26 13:03

OscarSan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!