before I added the product to the non-empty list, I tried to validate if the product id and name of the product already existed in the list by going through the list and if there is no such id and name in the list then added the product to the list, but, I got this error #ConcurrentModificationException
-thanks for advance
import java.util.ArrayList;
import java.util.Iterator;
public class ProductList implements Iterator<Product> {
private ArrayList<Product> productListArray = new ArrayList<>();
/* Singleton Design begin */
private static ProductList productListSingleton;
private ProductList() {
}// end of private constructor
public static ProductList instance() {
if (productListSingleton == null) {
productListSingleton = new ProductList();
}
return productListSingleton;
}
/* Singleton Design Phase end */
/*
* method add product into list
*
* @param Product Type
*/
public void addProduct(Product product) {
// if the list is empty just add the product into the list
if (productListArray.isEmpty()) {
productListArray.add(product);
}
/*
* add product only if the id and name not existed in the productList
*/
else {
for (Product product1 : productListArray) {
if (product1.getProductId() == product.getProductId()) {
System.out.println(" the product is already in the list");
}
else if (product1.getProductName().equals(product.getProductName())) {
System.out.println("choose another name for product");
}
else {
productListArray.add(product);
}
}
}
} // end of addProductMethod
/*
* remove the product from the ProductList Parameter product id
*/
public void remove(int productId) {
Iterator<Product> iteratorList = productListArray.iterator();
while (iteratorList.hasNext()) {
Product product = iteratorList.next();
if (product.getProductId() == productId)
iteratorList.remove();
} // end of while
} // end of remove method
/* retrieve the productlist */
public void retrieve() {
Iterator<Product> iteratorList = productListArray.iterator();
while (iteratorList.hasNext()) {
System.out.println(iteratorList.next());
}
}
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
if (next() == null) {
return false;
}
else {
return true;
}
}
@Override
public Product next() {
// TODO Auto-generated method stub
return next();
}
}
Aucun commentaire:
Enregistrer un commentaire