java - 为 ArrayList 中的每个对象打印不同的单词
问题描述
我有多个客户端对象。每个客户端对象都有一个名为 shoppingCart 的 ArrayList。这些 ArrayList 由我制作的 Product 类的对象填充。这些产品可以是衬衫、牛仔裤或裙子类(都继承产品)。我想将每个客户在他的购物车上的内容打印为字符串。例如,如果客户在他的购物车中有一件衬衫和一条裙子对象,控制台将打印:“购物车的内容:衬衫,裙子”我该如何完成呢?
解决方案
示例代码:
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]
推荐阅读
- c - 在 malloc 的返回值类型周围添加括号
- artifactory - Artifactory 和 Xray 可以使用通用的 RDS PostgreSQL 实例吗?
- mysql - mysql 安装损坏,导致 mysql 无法卸载
- javascript - 从 html 中的 app.js 调用函数时函数未定义和错误
- installation - 排查 Debian Preseed Late_command
- f# - 如何在不将结果传递给 F# 中的调用者的情况下捕获特定类型的异常?
- python - Python/Panda 字符串拆分 - 保留拆分器(分隔符)
- arrays - 下标值不是指针、数组,也不是向量,只是两个基本数组,
- regex - 用于解析逻辑表达式的正则表达式
- android - 在购买的源代码上没有“生成签名包/apk”选项