[英]How can I accept an argument list in a constructor and add it to a collection in Java?
I'm trying to make a constructor that would accept any number of variables of class "Item" as a variable argument list and add them to appropriate collection.我正在尝试创建一个构造函数,该构造函数将接受任意数量的 class“Item”变量作为变量参数列表并将它们添加到适当的集合中。 What would be the best way to go about it? go 最好的方法是什么?
My code so far:到目前为止我的代码:
import java.util.List;
public class Order {
private static long counter;
private final long orderNumber;
private final List<Item> items;
public Order(long counter, long orderNumber, Item... args) {
this.counter = counter;
this.orderNumber = orderNumber;
items{
list.add(Item);
}
}
}
Item... args
should be fine.. You can then just do this Item... args
应该没问题.. 然后你可以这样做
this.items = Arrays.asList(args);
… instead of the static items
block. …而不是 static items
块。
See similar code run live at IdeOne.com .查看在 IdeOne.com 上实时运行的类似代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.