簡體   English   中英

為 ArrayList 中的每個 object 打印不同的單詞

[英]Printing a different word for each object in an ArrayList

我有多個客戶端對象。 每個客戶端 object 都有一個名為 shoppingCart 的 ArrayList。 這些 ArrayList 由我制作的 class 產品的對象填充。 這些產品可以是 class 襯衫、牛仔褲或裙子(均繼承產品)。 我想打印每個客戶在他的購物車上的內容作為字符串。 例如,如果客戶在他的購物車中有一件襯衫和一條裙子 object,控制台將打印:“購物車的內容:襯衫,裙子”我如何完成此操作?

示例代碼:

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()));

    }


}

Output:

Contents of cart:  [PANT, PANT, SHIRT]

你可以做這樣的事情。 多態性的一個例子:

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);
}

我認為這可以通過使用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, ","));

我有多個 Client 對象。 每個客戶端對象都有一個名為shoppingCart 的ArrayList。 這些 ArrayList 由我創建的 Product 類的對象填充。 這些產品可以是襯衫、牛仔褲或裙子類(均繼承產品)。 我想將每個客戶在他的購物車上的內容打印為字符串。 例如,如果客戶在他的購物車中有一件襯衫和一條裙子對象,控制台將打印:“購物車的內容:襯衫,裙子”我該如何實現?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM