• Post Reply Bookmark Topic Watch Topic
  • New Topic

ArrayList problems  RSS feed

 
Dane Ensign
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, Im new to java. Im trying to use an ArrayList<Item> as a private member, where Item is a class that I built. Basically, in main when I add an item to a local ArrayList it works fine. But when I call a method in a class that has an ArrayList as a private member and I try to add an Item to the classes private ArrayList it throws a NullPointerException. I dont know how to describe it very well, so I attached a simple example that reproduces my problem.

Please can someone have a look and tell me where Im making my mistake?
Thank you in advance for any help you can offer.

http://www.rafb.net/paste/results/BFCRZm96.html

Best regards,

Dane Ensign
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dane,

Welcome to JavaRanch!

First, let me point out that you can paste code right into your messages here at the Ranch; if you enclose them in [CO DE] [/CO DE] tags, the formatting will be preserved (remove the space between "CO" and "DE".)

Second, as to your problem: this is a pretty common mistake. Your Cart class has a member "items" that is never initialized, so when add() tries to use it, there's a NullPointerException. "But", you say, "I initialize it right there in Cart's constructor!!!" As it turns out, though, you dont: you declare and initialize a local variable named "items" which hides the member inside the constructor; the member is never initialized as a result. To be painfully clear, the line

ArrayList<Item> items = new ArrayList<Item>();

in your Cart constructor should be just

items = new ArrayList<Item>();
 
Dane Ensign
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ernest, It works now. I was so stuck on the problem I could not see that. Thank you very much. Thank you also for the speedy reply.


Dane
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!