简体   繁体   English

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

[英]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.

相关问题 Java - 如何使用 3 参数构造函数来设置 2 个实例变量 - Java - How can I use a 3 argument constructor to set 2 instance variables 如何创建一个 Java 列表/映射/集合,我可以在其中修改值但不能添加或删除元素? - How can I create a Java List/Map/Collection in which I can modify the values but not add nor remove elements from it? Java:构造函数和参数列表错误 - Java: constructor and argument list error 如何在构造函数中传递参数? - How can I pass argument in the constructor? 如何测试 Java 集合是否支持添加操作? - How can I test whether a Java collection supports the add operation? 如何在Java中的复杂集合mongodb中排序并获取列表? - How can I sort and get a list in complex collection mongodb in java? 当我需要使用带有参数的构造函数时,如何使用Rhino子类化(扩展)Java类? - How can I subclass (extend) a Java class using Rhino when I need to use a constructor that takes an argument? 为什么不能在子类构造函数中添加额外的参数验证? - Why can't I add extra argument validation in the subclass constructor? 如何在 Java 中接受任意数量的参数作为 Int,例如添加数字? - How can I accept any amount of Arguments in Java as Int, to for example add the numbers? 如何说服Java构造函数接受包含其类实现特定接口的对象的列表 - How to convince a Java Constructor to accept a List containing objects whose Class implements a certain Interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM