Java Bootcamp – Workbooks and Challenges
)}

Shopping Cart – Part 4

Prerequisite: you completed the lesson: The equals() method.

Background

The default equals() method compares the references of two objects.

The Bug

contains uses the default equals method to compare Item objects. So, it compares the reference of each Item against the Item parameter.

Screen Shot 2021-06-20 at 12.09.15 AM.png

The Solution

Customize the equals() method for objects of the Item class. Then, contains will use your equals() method to compare Item objects.

Task 1 – Customize equals()


The equals() method must:

  • return false if the parameter is null.

  • return false if the parameter is not an instance of Item.

  • Otherwise, typecast the parameter to the type: Item.

  • Compare every field from both objects.

  • return the result.

Task 2 – Test your code


Task 3 – Visualize the runtime


See the solution video. It lets you visualize how contains runs your equals method behind the scenes.

Feedback Summary
4.8
39 students
5

92%
4

3%
3

0%
2

0%
1

5%
Written Reviews
There are no written reviews yet.