I am a Java newbie.. But I am sure I can get this done much efficient manner.
The purpose of this method is to add the product with an unique Id. If I the product as duplicate I should thrown an exception. Well, this sequence is not for multi-threaded environment.
public void addProduct(Product product)
throws ProductAlreadyExistsException {
product.id = ++nextId;
this.id = product.id;
Iterator<Product> it = allProducts.iterator();
Product p= null;
boolean flag= false;
if (!allProducts.isEmpty()) {
while(it.hasNext()){
p= it.next();
if ( p.getName() == product.getName())
throw new ProductAlreadyExistsException(p.getName());
else
flag = true;
}
}
else
allProducts.add(product.id-1, product);
if(flag){
allProducts.add(product.id-1, product);
}
}
What I want is something like this.
for (Product p : allProducts) {
if (p.getName() == product.getName() ) {
throw new ProductAlreadyExistsException(p.getName());
}
allProducts.add(p);
}
}
This does not work. Thanks for guiding me..