Reputation: 4778
I get a java.lang.NullPointerException
in my Class Article in line 5
.
In one class I create the object Article article = new Article()
,
then I call article.addPrice(quantity, price);
with quantity
being an Integer with the value '1
' and price
being a Float with the value '1.32
'.
1: public class Article {
2: private List prices;
3: public void addPrice(Integer quantity, Float qtyPrice){
4: Price price = new Price(quantity, qtyPrice);
5: this.prices.add(price);
6: }
7: }
Upvotes: 0
Views: 213
Reputation: 3589
In your code, you have just declared the list prices and not initialized it.
Use following corrected code :
1: public class Article {
2: private List<Price> prices = new ArrayList<Price>();
3: public void addPrice(Integer quantity, Float qtyPrice){
4: Price price = new Price(quantity, qtyPrice);
5: this.prices.add(price);
6: }
7: }
so till the time you do new ArrayList(), you have null in prices and you are trying to invoke .add(price) on null in line 5, hence the NullPointerException.
Upvotes: 0
Reputation: 1778
public class Article
{
private List<Price> prices = new ArrayList<Price>();
public void addPrice( Integer quantity, Float qtyPrice )
{
Price price = new Price( quantity, qtyPrice );
prices.add( price );
}
}
Unless you vastly oversimplified the problem, I can't think of any reason the above would not work.
Upvotes: 2
Reputation: 2579
You have not initialized the private list variable. Insert this as the first lines in addPrice
:
if (prices == null) {
prices = new ArrayList<Price>();
}
This will ensure the prices list is initialized prior to being accessed.
Upvotes: 1
Reputation: 20792
you need to initialize the prices list.
prices = new ArrayList<Price>();
Upvotes: 7
Reputation: 1554
The 'prices' list is not initialized which causes the null reference.
Upvotes: 3
Reputation: 70584
Your code never assigns prices
, therefore the field still contains its initial value, which is null
.
In plain english, you program would read: Create a new price object and add it to the list I assigned to prices
. You didn't assign a list, and therefore the computer can't know which list to add to ...
Upvotes: 5