Search code examples
javaswingbluej

create objects within code and add to arraylist, BlueJ


I am wanting to have objects already created in the code so I don't have to construct each object but I don't know how to add them to an array List, this is what I have so far:

public class MenuItem
{    
    private String foodName;
    private String foodType;
    private float price;
    private int calories;    


    public MenuItem(String nameFood, String typeFood, float foodPrice, int caloryCount)

    {     
    foodName = nameFood;
    foodType = typeFood;
    price = foodPrice;
    calories = caloryCount;

   } 

I had this set up but I am going to change it so I have a class with all the different menu sorts already added in so then all I have to do is add them to an Array List but I am not sure how to do this, just showing you this so you can have an idea of what I was planning on adding to the Array List.


Solution

  • If you are asking about how to create an ArrayList for your MenuItem class:

    AraryList<MenuItem> list = new ArrayList<MenuList>();
    

    To add MenuItem objects to your list:

    list.add(new MenuItem(foodName, foodType, price, calories));
    

    If you want to create sub-classing for your MenuItem:

    class MenuItem
    {
        //your class implementation
    }
    
    class SubMenuItem extends MenuItem
    {
        //your class implementation    
    }
    
    ArrayList<MenuItem> list = new ArrayList<MenuItem>();
    list.add(new MenuItem(foodName, foodType, price, calories));
    list.add(new SubMenuItem( /*your arguments*/ ));