Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何接受构造函数中的参数列表并将其添加到Java中的集合中?_Java_List_Collections_Constructor - Fatal编程技术网

如何接受构造函数中的参数列表并将其添加到Java中的集合中?

如何接受构造函数中的参数列表并将其添加到Java中的集合中?,java,list,collections,constructor,Java,List,Collections,Constructor,我试图创建一个构造函数,它将接受类“Item”中任意数量的变量作为变量参数列表,并将它们添加到适当的集合中。最好的办法是什么 到目前为止,我的代码是: import java.util.List; public class Order { private static long counter; private final long orderNumber; private final List<Item> items; public Order

我试图创建一个构造函数,它将接受类“Item”中任意数量的变量作为变量参数列表,并将它们添加到适当的集合中。最好的办法是什么

到目前为止,我的代码是:

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);
        }

    }
}
import java.util.List;
公共阶级秩序{
专用静态长计数器;
私有最终长订单号;
私人最终清单项目;
公共订单(长计数器、长订单号、项目…参数){
this.counter=计数器;
this.orderNumber=订单号;
项目{
列表。添加(项目);
}
}
}

项目。。。args
应该可以。。然后你就可以这么做了

this.items = Arrays.asList(args);
…而不是静态


请参见类似内容。

这有问题吗?
项。。。args应该足够了,否?什么是计数器?如果您试图计算有多少订单,这将不起作用。可能还有
Arrays.asList(args)
good point,在将来需要更改列表(项目)时编辑它,这不是最佳解决方案,因为数组。asList(args)返回一个固定长度的数组(与添加和删除操作一起应用时引发unsupportedoperationexception)@Arthurofos你认为这在当前环境中是个问题吗?你认为他会使用构造函数然后扩展它吗?我的意思是你是对的,但是……你有什么建议?@Hamza如果以后需要一个可调整大小的
列表
,只需将固定大小的列表传递给
列表
的合适实现的构造函数,如下:
List resizeblelist=newarraylist(fixedSizeArray);
一般来说,默认情况下的不变性是最好的,直到确定对可变性的实际需要。因此我会使用:
this.items=List.of(args);