首页 > 解决方案 > 为 ArrayList 中的每个对象打印不同的单词

问题描述

我有多个客户端对象。每个客户端对象都有一个名为 shoppingCart 的 ArrayList。这些 ArrayList 由我制作的 Product 类的对象填充。这些产品可以是衬衫、牛仔裤或裙子类(都继承产品)。我想将每个客户在他的购物车上的内容打印为字符串。例如,如果客户在他的购物车中有一件衬衫和一条裙子对象,控制台将打印:“购物车的内容:衬衫,裙子”我该如何完成呢?

标签: javastringarraylist

解决方案


示例代码:

public enum ProductType {
    PANT,
    SHIRT,
    SKIRT,
    TSHIRT,
}

public class Product {
    private ProductType productType;

    public Product( ProductType productType) {
        this.productType = productType;
    }

    public ProductType getProductType() {
        return productType;
    }
}

public class Pant extends Product {
    private int size;

    public Pant(ProductType productType, int size) {
        super(productType);
        this.size = size;
    }

}

public class Shirt extends Product {
    private int size;

    public Shirt(ProductType productType, int size) {
        super(productType);
        this.size = size;
    }

}

public class App {
    public static void main(String[] args) {
        List<Product> cart = List.of(new Pant(ProductType.PANT, 100),
                new Pant(ProductType.PANT, 101),
                new Shirt(ProductType.SHIRT, 42));

        System.out.println("Contents of cart:  " +
                cart.stream()
                .map(Product::getProductType)
                .collect(Collectors.toList()));

    }


}

输出:

Contents of cart:  [PANT, PANT, SHIRT]

推荐阅读