[英]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. 我已经设置好了,但是我要更改它,所以我有一个已经添加了所有不同菜单类别的类,所以我要做的就是将它们添加到数组列表中,但是我不确定如何做到这一点,只是向您展示此内容,这样您就可以了解我计划添加到“阵列列表”中的内容。
Do you mean a static List like this? 您是说这样的静态列表吗?
public class Main {
public static final List<MenuItem> items;
static {
items = new LinkedList<>();
items.add(new MenuItem("Steak", "Meat", 13.50f, 378));
items.add(new MenuItem("Bread", "Grain", 2.50f, 79));
items.add(new MenuItem("Rice", "Grain", 4.50f, 206));
}
}
If you are asking about how to create an ArrayList for your MenuItem
class: 如果您询问如何为
MenuItem
类创建ArrayList:
AraryList<MenuItem> list = new ArrayList<MenuList>();
To add MenuItem objects to your list: 要将MenuItem对象添加到列表中:
list.add(new MenuItem(foodName, foodType, price, calories));
If you want to create sub-classing for your MenuItem: 如果要为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*/ ));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.