equal() method is used in Java to compare the equality of two objects. It returns a Boolean value indicating whether they are equal. The equal() method performs comparisons by checking object references, types, and delegation to subclasses. For custom classes, you can customize comparison rules by overriding the equal() method, following the principles of reflexivity, symmetry, transitivity, and consistency.
The role of the equal() method in Java
In Java, the equal() method is the Object class The core method, which is used to compare two objects for equality. This method returns a Boolean value indicating whether the two objects are equal.
Specific implementation
equal() method compares two objects through the following steps:
Override the equal() method
For custom classes, you can customize the comparison rules by overriding the equal() method. The overridden equal() method should adhere to the following principles:
Example
The following is an example of a custom class that overrides the equal() method:
<code class="java">class Person { private String name; private int age; @Override public boolean equals(Object obj) { if (obj instanceof Person) { Person other = (Person) obj; return this.name.equals(other.name) && this.age == other.age; } return false; } }</code>
In this example, equal The () method compares the name and age fields of two Person objects to determine equality.
The above is the detailed content of What does equal mean in java?. For more information, please follow other related articles on the PHP Chinese website!