I wanted to optimize the code a bit. All trying to do is remove the product from the array.
When I call the method deleteProduct(prod.getId())
, it should delete product that I added first.
I can use the for loop, then how would delete the product in the array. Any pointers, please?
public void deleteProduct(int productId) throws ProductNotFoundException {
Iterator<Product> it = allProducts.iterator();
Product p= null;
int pid = productId;
int i = 0;
if (!allProducts.isEmpty()) {
while(it.hasNext()){
p= it.next();
i= allProducts.indexOf(p);
if (p.getId().equals(productId)){
i= allProducts.indexOf(p);
allProducts.remove(i);
System.out.println("Successfully removed the product " + pid);
return;
}
}
}
throw new ProductNotFoundException ("No Such Product");
}