Reputation: 303
I have some code similar to this:
ArrayList<SomeType> toGetSizeOf = new ArrayList<SomeType>();
int size = toGetSizeOf.size();
However, the second line is giving me a NullPointerException. Is there some way to avoid this, to basically tell if the ArrayList has been initialized but has not as of yet had anything added to it yet? (I have an if
/else
statement dependent on this).
Thanks in advance!
Upvotes: 0
Views: 570
Reputation: 6928
I think perhaps something else is wrong in your code.
The following works fine:
ArrayList<String> toGetSizeOf = new ArrayList<String>();
int size = toGetSizeOf.size();
System.out.println(size);
Which gives 0.
Debug your code and check what is actually null. I suspect it's your toGetSizeOf.
Upvotes: 2
Reputation: 347332
If you having issues with a NullPointerException
then you should be checking for it first
You could use...
int size = 0;
if (toGetSizeOf != null) {
size = toGetSizeOf.size();
}
or...
int size = toGetSizeOf == null ? 0 : toGetSizeOf.size();
You could also use ArrayList#isEmpty
which returns a boolean
true
, if the list is empty (size == 0
) or false
if it is not, depending on your needs
Upvotes: 0