0

I've a Class called Products. This class has a name and a price. I can create a product the following way:

Product book = new Product();
book.setName("book");
book.setPrice(3);

After that I'm supposed check if this product already exists in the ArrayList I'm supposed to save it to and if it doesn't, then I just put it there. I'm supposed to do this using the following:

public boolean equals(Object obj){

}

The problem is, how am I supposed to do it, if the ArrayList I'm supposed to save the product in, is created and initialised in the public static void main while this boolean is created before the ArrayList even exists?

Should I just make the Class itself an ArrayList, like so?

public class ArrayList<Product>{
}

4 Answers 4

3

Don't worry about it's existence. Since you are overiding equals method in your Product class, You can try doing this below

if(yourArayList.contains(book)){
   // it existed in the list
 }else{
   yourArayList.add(book);
}

When you call the contains method it internally calls the equals method of Product method vs the object being passed to it.

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

1 Comment

A bit short on the explaining, but thank you nonetheless. :3
1

This boolean is not created before your ArrayList exists.

You need to overwrite the equals() method of Product like this:

@Override
public boolean equals(Object obj) {
    if(obj == this) return true; // Both objects have the same reference -> the objects are equal
    if((obj == null) || (obj.getClass() != this.getClass())) return false; // Classes are different -> objects are different
    Product p = (Product) obj; // Cast obj into Product
    if( (this.getPrice() == p.getPrice()) && (this.getName().equals(p.getName())) ) return true; // Price and name are the same -> both products are the same
    return false; // At this point the two objects can't be equal
}

This is how you create an ArrayList:

ArrayList<Product> products = new ArrayList<Product>();

And this is how you add a Product when it doesn't exist in the list:

    if(!products.contains(yourProduct)){ // Checks if yourProduct is not contained in products
        products.add(yourProduct); // adds yourProduct to products
    }

3 Comments

Thank you very much for taking time to write this. The explanation using comments on each line really helped me understand. :3
Note that you should check for obj == null before calling obj.getClass(), to avoid a NullPointerException. You also often put in a check for obj == this as the very first check, as an object should be equal to itself, and this is a much lighter weight thing to check than the rest of the method.
@AndyTurner thanks for noting that, I forgot about that. I edited my answer accordingly.
1

this boolean is created before the ArrayList even exists?

You misunderstood the way equals works. It does not "create" a boolean until you call it with some object as an argument, and it returns a boolean based on the attributes of the object that you pass.

When you define your equals method you provide code to decide equality, but you are not deciding anything at that moment:

@Override
public boolean equals(Object obj){
    if (obj == this) return true
    if (!(obj instanceof Product)) return false;
    Product other = (Product)obj;
    if (!other.getName().equals(getName())) return false;
    if (!other.getPrice() == getPrice()) return false;
    return true;
}
@Override
public int hashCode() {
    return 31*getName().hashCode() + getPrice();
}

Now you can use equals to deicide if a list has your Product in one of two ways:

  • Use contains - this method calls equals to check containment, or
  • Iterate all objects, and call equals manually.

1 Comment

Thank you kindly for the explanation. :3
1

You don't need to create your own ArrayList class. If you implement you equals right, it will be called to check if you have it in the list when you execute myList.contains(book)

Actually there is a structure that will let you skip performing the check in your code. You can use the java.util.HashSet. It ensures that no duplicates can be added. In addition it returns the boolean value saying if the element was added. E.g.

Set<Product> mySet = new HashSet<>(); 
boolean added = mySet.add(book);

Please don't forget the easy to follow rule - when defining the equals, define the hashCode too. If you use an IDE, you can generate them both easily.

1 Comment

I'd like to avoid using HashSet since I don't fully understand it yet, but I appreciate the help and time you took to write it. ^_^

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.