Results 1 to 2 of 2
  1. #1
    susan is offline Member
    Join Date
    Jul 2007
    Posts
    44
    Rep Power
    0

    Default ArrayList: Exception in thread "main" java.lang.NullPointerException

    Having a problem creating objects and storing them in an arraylist. I have no problem doing this with regular arrays, but whenever I try to use an arraylist I get the error:

    Java Code:
    Exception in thread "main" java.lang.NullPointerException
    at ZBay.printItems(main.java:41)
    at main.processCommands(main.java:17)
    at main.main(main.java:10)
    Java Code:
    import java.util.*;
    
    public class main
    {
    	public static void main(String[] parms)
    	{
    		ZBay store;
    
    		store = new ZBay();
    		processCommands(store);
    
    		System.out.println("\nProgram completed normally.");
    	}
    
    	public static void processCommands(ZBay store)
    	{
    		store.printItems();
    	}
    }
    
    class ZBay
    {
    	ArrayList itemList;
    
    	public ZBay()
    	{
    		createItemList();
    	}
    
    	public void createItemList()
    	{
    		ArrayList itemList = new ArrayList();
    
    		itemList.add(new Item("test", "test", "test", "test"));
    	}
    
    	public void printItems()
    	{
    		Item currentItem;
    
    		currentItem = (Item) itemList.get(0);
    
    		System.out.println(currentItem.toString());
    	}
    }
    
    class Item
    {
    	String itemId;
    	String itemName;
    	String itemPrice;
    	String vendorId;
    	String purchaserId;
    
    	public Item(String itemId, String itemName, String itemPrice, String vendorId)
    	{
    		this.itemId = itemId;
    		this.itemId = itemName;
    		this.itemPrice = itemPrice;
    		this.vendorId = vendorId;
    	}
    
    		public String toString()
    		{
    			return itemId + " " + itemName + " " + itemPrice + " " + vendorId;
    		}
    }
    Any help just pointing out where I am going wrong would be great!

    Thanks.

  2. #2
    akaruppa is offline Member
    Join Date
    Jul 2007
    Posts
    2
    Rep Power
    0

    Default

    Hi,
    I think the problem is in
    public void createItemList()

    In this method, you are defining a local variable
    ArrayList itemList = new ArrayList();

    Hence the member variable itemList is still empty..

Similar Threads

  1. Replies: 3
    Last Post: 01-29-2008, 02:37 AM
  2. Replies: 1
    Last Post: 08-07-2007, 08:10 AM
  3. Replies: 2
    Last Post: 08-01-2007, 06:26 AM
  4. Replies: 1
    Last Post: 07-31-2007, 02:54 PM
  5. Replies: 1
    Last Post: 07-25-2007, 11:55 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •