将多个参数传递到数组列表中 (Java)

huangapple go评论112阅读模式
英文:

Pass Multiple Parameters into an Array List (Java)

问题

我正在尝试设置一个数组列表,用于存储购物清单上的项目。我希望该列表能够存储每个项目的名称、价格和税收信息。是否可以设置一个ArrayList来同时接受字符串和整数参数?我已经在下面包含了我的代码:

public class ItemList
{
    // 实例变量 - 用你自己的内容替换下面的示例
    private ArrayList<String> items;
    private String itemName;
    private int cost;
    private String taxable;

    /**
     * ItemList类的构造函数
     */
    public ItemList()
    {
        items = new ArrayList<>();
    }

    /**
     * 向ItemList中添加一个项目
     */
    public void addItem(String itemName, int cost, String taxable)
    {
        items.add(itemName, cost, taxable);
    }
}
英文:

I am trying to set up an array list that will store items on a grocery list. I would like the for the list to store the name, price, and tax information for each item. Is it possible to set up an ArrayList so that it accepts both String and integer parameters? I've included my code below:

public class ItemList
{
// instance variables - replace the example below with your own
private ArrayList&lt;String&gt; items;
private String itemName;
private int cost;
private String taxable;


/**
 * Constructor for objects of class ItemList
 */
public ItemList()
{
   items=new ArrayList&lt;&gt;();
    
}

/**
 * Adds an item to the ItemList
 */
public void addItem(String itemName, int cost, String taxable)
{
    items.add(itemName, cost, taxable);
}
}

答案1

得分: 2

以下是翻译好的内容:

正确的方法是创建一个Item类,并拥有一个这些类的ListItem类应该有一个接受必要变量的构造函数。

然后你可以这样做:

private ArrayList<Item> items;
// ...
public void addItem(String itemName, int cost, String taxable)
{
    items.add(new Item(itemName, cost, taxable));
}
英文:

The correct way would be to create a Item class and have a List of these. The Item would have a constructor that takes the necessary variables.

Then you could do

private ArrayList&lt;Item&gt; items;
.....
public void addItem(String itemName, int cost, String taxable)
{
    items.add(new Item(itemName, cost, taxable));
}

huangapple
  • 本文由 发表于 2020年10月23日 08:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64492438.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定