x.equals(x) must return true.x.equals(y) returns true if and only if y.equals(x) returns true.x.equals(y) and y.equals(z) return true, then x.equals(z) must return true.
public boolean equals(Object obj) {
return (this == obj);
}
The java.util.Objects class provides utility methods to check if two objects are equals or deeply equals (in case of arrays):
public static boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
public static boolean deepEquals(Object a, Object b) {
if (a == b)
return true;
else if (a == null || b == null)
return false;
else
return Arrays.deepEquals0(a, b);
}
The java.util.Arrays class provides utility methods to check if two arrays are equals
(including specific overloaded methods for each primitive type).
It also provides a utility method to check if two arrays are deeply equals (nested arrays).
import java.util.Objects;
class P {
private Integer id = 1;
public Integer getId() {
return id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof P)) {
return false;
}
P p = (P) obj;
return Objects.equals(this.getId(), p.getId());
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
class C extends P {
private String code = "default";
public String getCode() {
return code;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
C c = (C) obj;
if (!super.equals(obj)) {
return false;
}
return Objects.equals(this.getCode(), c.getCode());
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), code);
}
}
!(obj instanceof ClassName) to allow subclass equality.getClass() != obj.getClass() for strict type checking (no subclass equality).
import org.apache.commons.lang3.builder.EqualsBuilder;
class P {
Integer id = 1;
public Integer getId() {
return id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof P)) {
return false;
}
P p = (P) obj;
return new EqualsBuilder().append(this.getId(), p.getId()).isEquals();
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
class C extends P {
String code = "default";
public String getCode() {
return code;
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj))
return false;
C c = (C) obj;
return new EqualsBuilder().append(this.getCode(), c.getCode()).isEquals();
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), code);
}
}