PDA

View Full Version : Java - ArrayList problem


BrianHine
11-03-2006, 07:25 AM
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: 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)

Here is a skeleton of what I am trying to do:

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 :)

ess
11-03-2006, 10:17 AM
Check the following method

public void createItemList()
{
ArrayList itemList = new ArrayList();

itemList.add(new Item("test", "test", "test", "test"));
}

the first line of the method...it seems that you have already defined itemList to be of type ArrayList. you should change it to the following

this.itemList = new ArrayList();


Also, since you are storing objects of type Item, you should declare the ArrayList object like so.

ArrayList<Item> itemList = new ArrayList<item>();

This ensures that you can only store objects of type Item and you wouldn't need to unbox objects when needed. for more information on this, please click here (http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html)

Hope that helps.

:thumbsup:

FatMummy
12-08-2006, 07:03 AM
I have the same problem. That does help. Thanx a lot.