lundi 14 décembre 2020

What am I doing wrong with this variable argument constructor?

This is homework, so please keep that in mind: I'm trying to use the Builder pattern to initialize a constructor with a variable number of Bag items. I keep getting an exceptionInInitializer. What am I missing?

This is how I'm using it (in a junit test) to initialize objects for further tests:

private static final Order ORDER1 = new Order.Builder(BAG1).addBag(BAG2).build();

This is the Builder: Builder in Order class:

public class Order {
   private final List<Bag> bags;

   public static class Builder {
        private List<Bag> bags;
        private List<Bag> moreBags;

        public Builder(Bag bag) {
            bags = List.of(bag);
            bags.addAll(moreBags);
        }

        public Builder addBag(Bag bag) {
            moreBags.add(bag);
            return this;
        }

        public Order build() {
            return new Order(this);
        }
    }

    private Order(Builder builder) {
        bags = builder.bags;
    }

   \\remaining methods

} \\end of Order class

This was the original Builder. It results in the same error.

public static class Builder {
        private List<Bag> bags;

        public Builder(Bag bag) {
            bags = List.of(bag);
        }

        public Builder addBag(Bag bag) {
            bags.add(bag);
            return this;
        }

        public Order build() {
            return new Order(this);
        }
    }

Aucun commentaire:

Enregistrer un commentaire