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