1

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..

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It is much better to implement equals() method in Product, so they can compare themselves to other objects. While doing so, also remember to implement hashCode. IDEs can automatically generate those two methods for you. About the equals and hashCode contract, read this.
I made the above changes and it worked much better. Thanks a lot
3

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.

3 Comments

Appart from knowing that there are no duplicates, a Set will also be more efficient on lookups.
Unfortunately, the id is not getting created.. Id is null.. Should I change the constructor. I have the following code in the contructor. public Product(String name, double price, DeptCode code) { this(null, name, price, code); } public Product(Integer id, String name, double price, DeptCode code) { this.id = id; this.name = name; this.price = price; this.dept = code;
Wouldn't the ID be bound to the Product object anyway?
0

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.