ADD OBJECT INTO AN ARRAYLIST ERROR USING JAVA

ben reitman

Total Post:96

Points:676
Posted by  ben reitman
Java 
 994  View(s)
Ratings:
Rate this:

I have a problem using add an object of the class Fish to an arraylist call itemList.

My Code: -

public static void main(String[] args) 
{
    ItemList i1 = new ItemList("item#1");
}

Below my class and Constructor: -

public class ItemList
{
    protected static String name;
    protected static int number;
    protected static List<ItemList> itemList = new ArrayList<ItemList>();
    public ItemList(String in)
    {
        name = in;
        number = 15;
        itemList.add(name, number);
    }
}

How do I add objects to an arraylist properly?

  1. Samuel Fernandes

    Post:159

    Points:1117
    Re: Add Object into an ArrayList error using java

    Firstly you shouldn’t be name and number is static (unless you want all the ItemList to have the same name/number but then creating more than 1 instance of that class would be a waste of resources)!

    Secondly, change:

    itemList.add(name, number);

    To:

    itemList.add(this);

    itemList can hold references to objects of type ItemList. If you try to add "name, number" Java doesn't know you mean a ItemList:-)

    this points to the objects that is currently being created in the constructor.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!