[go: up one dir, main page]

0% found this document useful (0 votes)
3 views18 pages

equals() and hashCode()

The document explains the importance of overriding the equals() and hashCode() methods in Java to ensure proper object comparison and storage in collections. It emphasizes that equals() checks for logical equality while hashCode() is used for efficient retrieval in hash-based collections. Both methods must be overridden together to maintain consistency, ensuring that equal objects yield the same hash code and can be correctly located in collections.

Uploaded by

srrm.nnn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views18 pages

equals() and hashCode()

The document explains the importance of overriding the equals() and hashCode() methods in Java to ensure proper object comparison and storage in collections. It emphasizes that equals() checks for logical equality while hashCode() is used for efficient retrieval in hash-based collections. Both methods must be overridden together to maintain consistency, ensuring that equal objects yield the same hash code and can be correctly located in collections.

Uploaded by

srrm.nnn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Collections

equals() and hashCode()

Copyright © Seán Kennedy


equals()
• Comparing two object references using the == operator
evaluates to true only when both references refer to the same
object i.e. == compares the bits in the references variables
themselves and they are either equal or they are not.

• The equals() in Object behaves in the same way i.e. equals()


in Object uses only the == operator for comparisons.

p1 reference
Person object
• Person p1 = new Person();
Person p2 = new Person();
Person object
p2 reference

Copyright © Seán Kennedy


equals()
• The String class has overridden equals(), which it inherits
from Object, so that you can compare two different String
objects to see if their contents are meaningfully equivalent.

• When you need to know if two references are identical, use


==

• When you need to know if two objects themselves (not the


references) are equal, use the equals() method.

Copyright © Seán Kennedy


equals()
• Bear in mind what we will be storing objects (as keys) in
Collections (such as HashMap) and searching/retrieving these
objects again later.

• For example, assume we do not override equals() and we


store an object of that type in a Collection and later attempt to
retrieve it - we are in trouble unless we have a reference to the
exact object we used when storing the key.

• This is because the search for the key/object will be based


on Object::equals() which, as we know, uses == on the
references for equality testing.
4

Copyright © Seán Kennedy


equals()

• Whereas, if you override equals(), when you need to search


for object X, you can just re-create a new instance that is
meaningfully equivalent to X and use that instance for the
search.

Copyright © Seán Kennedy


equals()
• If you want objects of your class to be used as elements in
any data structure that uses equivalency for searching for,
and/or retrieving an object, then you must override equals() so
that two different instances can be considered the same.

• That way, you can use one instance when you add it to a
Collection and essentially re-create an identical instance when
you want to do a search based on that object as the key.

Copyright © Seán Kennedy


equals()
• In summary:
 Object:equals() checks if two references are equal i.e. do they refer
to the same object?

 typically, this is not what you want so you must override equals()
• public boolean equals(Object obj)

 the Object passed in must be downcast to the relevant type; to do


this safely use instanceof

Copyright © Seán Kennedy


equals()

Copyright © Seán Kennedy


toString(), equals() and hashCode()
• Remember that toString(), equals() and hashCode() are all
public. Therefore the following is an illegal override :
 class Foo{boolean equals(Object o){return true;}} // should be
public

• The following is also an illegal override :


 class Foo{public boolean equals(Foo f){return true;}} // parameter
should be Object not Foo

Copyright © Seán Kennedy


hashCode()
• If two objects are considered equal using the equals()
method, then they must have identical hashcode values. If you
override equals(), override hashCode() as well.

• Hashcodes are used for improving performance in hash


based collections e.g. HashSet, HashMap. The hashcode
value is used to determine how the object should be stored in
the collection and the hashcode is used again to help locate
the object in the collection.

10

Copyright © Seán Kennedy


Understanding hashing
• Hashing is similar to putting items in buckets:
• the hashcode value determines which bucket the object is
stored in and later on, the hashcode value determines which
bucket is searched to locate the object.
• hashcodes are not necessarily unique so several objects can
land in the same bucket; this is where equals() comes into
play - the correct object is then located by using the equals()
method
1. find the right bucket (with hashCode())
2. search the bucket for the right element (using equals())
• thus, for an object to be located, the search object and the
object in the collection must have the same hashcode and
return true for equals().
11

Copyright © Seán Kennedy


Understanding hashing
• Assume we are storing names according to the following
hashing calculation algorithm - A=1, B=2 etc…
• The numbers associated with each letter are added
together to give the hashcode (bucket number)
• Bob = B(2) + O(15) + B(2) = 19
• Amy = A(1) + M(13) + Y(25) = 39
• May = M(13) + A(1) + Y(25) = 39

39 “Amy”, “May” 19 “Bob”

hashCode() equals()
12

Copyright © Seán Kennedy


hashCode()
• The default hashCode() method in Object always comes
up with a unique number for each object, even if the
equals() method is overridden and states that two or more
objects are equal.

• In other words, it does not matter how equal they are if


their hash codes do not reflect that (as you will be directed
to the wrong bucket). Therefore the hashCode() contract
states that, if two objects are equal, their hashcodes
must be equal as well.

13

Copyright © Seán Kennedy


hashCode()
• When calculating the hashcode in hashCode(), make
sure to use the same instance variables that you used in
equals(). Therefore, if two objects are equal (based on
their instance variables), then the two objects will have
the same hashcode value.

14

Copyright © Seán Kennedy


hashCode()
• Note: do not use transient instance variables in the
hashcode calculation as these are not serialised.

• For example, if a transient variable has 10 as its value at


the time you store the object in a HashMap, then you
serialise the object to disk (transient not serialised); you
then deserialise the object, the transient variable will get
a default value e.g. 0 and therefore the hashcode value
will be different when you go to locate that object (i.e.
wrong bucket).

15

Copyright © Seán Kennedy


This is the key part!

16

Copyright © Seán Kennedy


hashCode() summary
• hashCode() contract:
• the “contract” states that “two equal objects must have
the same hashcode”.
• public int hashCode() :
• by default, hashCode() in Object returns a unique integer
for objects.
• to be certain that your objects can be used in Collections
that use hashing, you must override both equals() and
hashCode() as both are used - hashCode() to find the
bucket and equals() to find the object in the bucket.
• the instance variables used in equals() must be used in
hashCode(); that way, equal objects will return the same
hashcode integer value.
17

Copyright © Seán Kennedy


ContactTest program

MutableFieldsTest program

18

Copyright © Seán Kennedy

You might also like