[英]arraylist within arraylist in Java
我必須創建一個Shops對象的數組列表,該對象具有名稱,描述和另一個product對象的arraylist。 addProduct方法留空,因為這是我面臨的問題。 我需要在使用Shops對象創建的商店陣列列表中選擇一個特定的商店名稱,然后在產品陣列列表中添加一個或多個產品。 我不知道如何才能做到這一點。 如果你們可以幫助我。
這是我到目前為止的代碼:
//class of shops but I removed the getters and setters to keep the code short
public class Shops {
private String name;
private String desc;
private ArrayList<Products> product;
public Shops(String name, String desc, ArrayList<Products> product) {
this.name = name;
this.desc = desc;
this.product = product;
}
//another class called Shop assistant which adds products to a specific shop
public class ShopAssistant {
ArrayList<Shops> shop = new ArrayList<>();
public void addShops(Shops shop) {
shop.add(shop);
}
public void addProduct(Products product ) {
//add products to product arraylist which should be linked to shop arraylist
}
您必須知道在哪里添加產品。 您必須將其添加到ArrayList內的Shop對象中,而不是添加到ArrayList中。 您可以通過ArrayList中的索引來獲得一家商店,因此您可能需要另一個int參數。
首先,您需要將'addProduct'方法添加到'Shop'類中,以將產品添加到商店的數組列表中。
然后,您可以在“ ShopAssistant”類中創建諸如“ addProductToShop”之類的方法,該方法接收一家商店和一種產品,並將該產品添加到該商店,例如,使用for循環查找該商店,然后使用“商店”類中的“ addProduct”方法。
我還建議將“商店”重命名為“商店”,將“產品”重命名為“產品”,以更清楚地說明其所擁有的內容。
public class Shop {
private String name;
private String description;
private ArrayList<Products> products;
public Shop(String name, String description, ArrayList<Products>products){
this.name = name;
this.description = description;
this.products = products;
}
//This is the main issue that you were missing.
//You need to have addProducts in both the shop and assistant.
public void addProducts(ArrayList<Products>newProducts){
newProducts.forEach((product) -> {
this.products.add(product);
});
}
}
public class ShopAssistant {
ArrayList<Shop> shops = new ArrayList<>();
public void addShop(Shop newShop){
shops.add(newShop);
}
//Call AddProducts for each shop in the list of shops that need products updated.
public void addProducts(ArrayList<Products>newProducts, ArrayList<Shop>shopsToAddTo){
shopsToAddTo.forEach((shop) -> {
shop.addProducts(newProducts);
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.