Reputation: 146
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..
Upvotes: 1
Views: 148
Reputation: 133
Makoto's answer is a simple way to make sure that an object is unique in a List
.
Additionally you need to make sure to implement the equals(Object obj)
method in the class of the objects, you want to add to the list. The List.contains()
method calls equals(yourObject)
on each object it contains and returns true
, as soon as equals(yourObject)
returns true for any of the objects in the List
.
Here you can see a good implementation of equals(Object obj)
you could use in your Product
class.
public class Product {
//Other methods here
public boolean equals(Object obj) {
if(this == obj)
return true;
if(obj == null)
return false;
if(this.getClass() != obj.getClass())
return false;
Product product = (Product)obj;
boolean result = true;
//Compare fields of this with fields of product and set result
return result;
}
}
Upvotes: 0
Reputation: 143
In Java, you use s1.equals(s2)
method to identify if two strings are equal.
if ( p.getName() == product.getName()) // This will always return false, because references are compared here
What you should do is:
if ( p.getName().equals(product.getName()) )
NOTE: I'm assuming that getName()
returns a string.
Upvotes: 3
Reputation: 106389
In general, there's no guarantee granted that a List
of any kind will contain only unique elements, but I would imagine you don't have to go through the process of creating an Iterator
.
Merely making use of List.contains()
is sufficient - if the list doesn't contain the element, add it in, otherwise, throw the exception*.
public void addProduct(Product theProduct) throws ProductAlreadyExistsException {
if(allProducts.contains(theProduct)) {
throw new ProductAlreadyExistsException("Not unique!");
}
allProducts.add(theProduct);
}
*: Throwing the exception is a bit silly IMO. That should only be reserved for truly exceptional behavior. You're probably better off with a Set
of some sort instead.
Upvotes: 3