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 16 - 22 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 21 the Equals method states that two Smartphone objects are considered identical if their model is the same.
  • The Contains method at lines 40, 45, 50, 55, 60 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.