How is this a nullpointerexception?
I'm really confused: I'm simply trying to add the names of each object in an ArrayList
to another ArrayList
.
for (int i = 0; i < availableParts.size(); i++) {
for (int j = 0; j < namesOfIngredients.size(); j++){
if (availableParts.get(i).getName() != namesOfParts.get(j)){开发者_开发问答
namesOfParts.add(availableParts.get(i).getName());
}
}//middle if statement makes sure there are no repeats
}
EDIT: I realize namesOfIngredients is null. However, I need it to start null -- this is how I am copying over the names. Can this just not be done this way?
Make sure that
- both lists
availableParts
andnamesOfIngredients
are notnull
- The list that you're adding elements to (
namesOfParts
) has been properly initialized with a constructor (is notnull
). - All elements inside these lists are not
null
And remember that String comparison is done with String.equals()
. Checking equality (==
) on two String objects will only return true if they are the same instance.
As a side note, you could consider using List.contains()
in order to find out if a certain part's name is on the namesOfIngredients
list. Also, maybe it's a typo, but you should be checking for an IndexOutOfBoundsException
at namesOfParts.get(j)
in that equality check.
You're trying to look at namesOfParts in the loop itself, but in the definition of the loop you're going to the length of namesOfIngredients. Is one of them null? I bet one is.
Given your edit - how do you declare namesOfIngredients?
It should be
Object namesOfIngredients = new Object();
not
Object namesOfIngredients;
availableParts.get(i) is probably null and therefore a getName() call results in a NPE.
We don't know: we can't see how availableParts
and namesOfParts
are initialized.
But we can tell you how to find out. Add print statements like this:
print "Before I try it"
print availableParts.get(i)
print namesOfParts(availableParts.get(i))
print "done"
when it NPE's you'll see exactly which one did the deed.
You seem to be invoking a number of methods within your loop, without checking that the object on which you are invoking it is NULL or not. It is ALWAYS advisable to do so (especially, if you are not sure about the contract of the object returned by a given method)
So, basically, whenever you do something like object.method()
and/or object.method1().method2()
, ensure that object
and/or object.method1()
is NOT NULL before invoking follow-up methods on their return values.
Also, you could break calls in the following manner, to better debug and catch NPEs at the exact location:
Object returnObj = object.method1();
Object anotherReturn = returnObj.method2();
精彩评论