Equals Method

The equals method is used to determine whether 2 objects of a class are the same.

Syntax

Objects equality

Let's look at the following example:

Output:

Explanation:

  • At lines 12 - 20 the equals method is defined. Two Smartphone objects are considered identical if they have the same model and price.
  • That's why only phone_2 and phone_3 are considered identical.

Equals And Contains Methods

It can be checked whether an object is contained in List collections via the equals and contains methods.

The rule whether an object is contained in the array is specified in the equals method.

Example:

Output:

Explanation:

  • At line 15 the equals method states that two Smartphone objects are considered identical if their model is the same.
  • The contains method at lines 46, 50, 54, 58, 62 relies on the equals method.
  • This means that a Smartphone object is considered to be contained in the list, if the list has an object with the same model.