I am trying to override equals method in Java. I have a class People
which basically has 2 data fields name
and age
. Now I want to override equals
method so that I can check between 2 People objects.
My code is as follows
public boolean equals(People other){
boolean result;
if((other == null) || (getClass() != other.getClass())){
result = false;
} // end if
else{
People otherPeople = (People)other;
result = name.equals(other.name) && age.equals(other.age);
} // end else
return result;
} // end equals
But when I write age.equals(other.age)
it gives me error as equals method can only compare String and age is Integer.
Solution
I used ==
operator as suggested and my problem is solved.
Item 10: Obey the general contract when overriding equals
Each instance of the class is inherently unique. This is true for classes such as Thread that represent active entities rather than values. The equals implementation provided by Object has exactly the right behavior for these classes.
There is no need for the class to provide a “logical equality” test. For example, java.util.regex.Pattern could have overridden equals to check whether two Pattern instances represented exactly the same regular expression, but the designers didn’t think that clients would need or want this functionality. Under these circumstances, the equals implementation inherited from Object is ideal.
A superclass has already overridden equals, and the superclass behavior is appropriate for this class. For example, most Set implementations inherit their equals implementation from AbstractSet, List implementations from AbstractList, and Map implementations from AbstractMap.
The class is private or package-private, and you are certain that its equals method will never be invoked. If you are extremely risk-averse, you can override the equals method to ensure that it isn’t invoked accidentally:
The
equals
method implements an equivalence relation. It has these properties:Reflexive: For any non-null reference value
x
,x.equals(x)
must return true.Symmetric: For any non-null reference values
x
andy
,x.equals(y)
must return true if and only if y.equals(x) returns true.Transitive: For any non-null reference values
x
,y
,z
, ifx.equals(y)
returnstrue
andy.equals(z)
returnstrue
, thenx.equals(z)
must returntrue
.Consistent: For any non-null reference values
x
andy
, multiple invocations ofx.equals(y)
must consistently returntrue
or consistently returnfalse
, provided no information used in equals comparisons is modified.For any non-null reference value
x
,x.equals(null)
must returnfalse
.Here’s a recipe for a high-quality equals method:
Use the
==
operator to check if the argument is a reference to this object. If so, return true. This is just a performance optimization but one that is worth doing if the comparison is potentially expensive.Use the
instanceof
operator to check if the argument has the correct type. If not, return false. Typically, the correct type is the class in which the method occurs. Occasionally, it is some interface implemented by this class. Use an interface if the class implements an interface that refines the equals contract to permit comparisons across classes that implement the interface. Collection interfaces such as Set, List, Map, and Map.Entry have this property.Cast the argument to the correct type. Because this cast was preceded by an instanceof test, it is guaranteed to succeed.
For each “significant” field in the class, check if that field of the argument matches the corresponding field of this object. If all these tests succeed, return true; otherwise, return false. If the type in Step 2 is an interface, you must access the argument’s fields via interface methods; if the type is a class, you may be able to access the fields directly, depending on their accessibility.
For primitive fields whose type is not
float
ordouble
, use the==
operator for comparisons; for object reference fields, call theequals
method recursively; forfloat
fields, use the staticFloat.compare(float, float)
method; and fordouble
fields, useDouble.compare(double, double)
. The special treatment of float and double fields is made necessary by the existence ofFloat.NaN
,-0.0f
and the analogous double values; While you could comparefloat
anddouble
fields with the static methodsFloat.equals
andDouble.equals
, this would entail autoboxing on every comparison, which would have poor performance. Forarray
fields, apply these guidelines to each element. If every element in an array field is significant, use one of theArrays.equals
methods.Some object reference fields may legitimately contain
null
. To avoid the possibility of aNullPointerException
, check such fields for equality using the static methodObjects.equals(Object, Object)
.First of all: you are not overriding
equals
, you are overloading it.Without seeing the actual declaration of
age
, it is difficult to say why are you getting the error.if age is int you should use == if it is Integer object then you can use equals(). You also need to implement hashcode method if you override equals. Details of the contract is available in the javadoc of Object and also at various pages in web.
Since I'm guessing
age
is of typeint
:Output: