Reputation:
I have to create an arraylist of Shops objects which have a name, description and another arraylist of products objects. The addProduct method is left blank because this is where I face a problem. I need to select a specific shop name in the shop arraylist created with Shops objects and then add one or more products in the arraylist of products. I don't understand how I can manage to do that. If you guys could help me.
This is the code I have so far:
//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
}
Upvotes: 1
Views: 189
Reputation: 21
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);
});
}
}
Upvotes: -1
Reputation: 530
You first need the 'addProduct' method to be in the 'Shop' class, to add a product to the shop's arraylist.
Then, you can create a method such as 'addProductToShop' in the 'ShopAssistant' class that takes a shop and a product, and adds the product to the shop e.g. use a for-loop to find the shop, and add the product using the 'addProduct' method from the 'Shop' class.
I would also advise renaming 'shop' to 'shops' and 'product' to 'products' to make it more clear what they hold.
Upvotes: 1
Reputation:
You have to know where to add the product. You have to add it to a Shop object inside the ArrayList, not to the ArrayList. You can get a shop by its index in the ArrayList, so you probably need another int parameter.
Upvotes: 1