【问题标题】:Printing a different word for each object in an ArrayList为 ArrayList 中的每个对象打印不同的单词
【发布时间】:2020-09-30 17:30:32
【问题描述】:

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

【问题讨论】:

标签: java string arraylist


【解决方案1】:

示例代码:

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]

【讨论】:

    【解决方案2】:

    我认为这可以通过使用instanceof 运算符来实现。您可以尝试这样做:

    public List<String> getContentsOfCart(List<Product> products) {
      List<String> result = new ArrayList<>();
      for (Product p : products) {
        if (p instanceof Skirt) {
          result.add("Skirt");
        } else if (p instanceof Shirt) {
          result.add("Shirt");
        } else if (p instancef Jeans) {
          result.add("Jeans");
        }
      }
      return result;
    }
    

    然后您可以像这样打印此列表:

    System.out.println("Contents of cart: " + Strings.join(result, ","));
    

    【讨论】:

      【解决方案3】:

      你可以做这样的事情。 多态性的一个例子:

      abstract class Product{
        abstract String getType();
      }
      
      class Shirt extends Product {
        String getType() {
          return "Shirt";
        }
      }
      
      class Skirt extends Product {
        String getType() {
          return "Skirt";
        }
      }
      

      当您遍历 shoppingCart 并打印类型时,您会得到相应的类型。

      for(Product p : shoppingCart) {
        System.out.println(p.getType);
      }
      

      【讨论】:

        猜你喜欢
        • 2017-09-06
        • 2018-10-30
        • 1970-01-01
        • 2020-08-09
        • 2019-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-02
        相关资源
        最近更新 更多