Skip to content

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. What would be the best way to go about it?

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;





Item... args should be fine.. You can then just do this

this.items = Arrays.asList(args);

… instead of the static items block.

See similar code run live at

9 People found this is helpful