While I’m working with my apprentices at the Software Guild, I’m helping our instructors train them for junior level positions. I love working with these guys and getting fresh perspectives of coding from them. One of them asked me to look at his code, as he was getting a bunch of garbage in the output.
After running through the code, I saw this:
[com.thesoftwareguild.sampleclass.SampleObject@5c647e05, com.thesoftwareguild.sampleclass.SampleObject@33909752, com.thesoftwareguild.sampleclass.SampleObject@55f96302]
This was the garbage that my apprentice was talking about. This made me laugh, fondly remembering my early days as a dev and calling it garbage as well.
So… What is this garbage?!?
This is a collection of objects, as the comma-delimited list suggests. The collection needs to be looped through in order to be outputted properly. This is what happens when you try to output a raw object.
Ok… so I need to run the collection through a loop to get the properties of each object in the collection. I get that. But what’s this garbage representing?
Let’s look at the parts of this object:com.thesoftwareguild.sampleclass.SampleObject@55f96302
com.thesoftwareguild.sampleclass.SampleObject
– This is a SampleObject class in the package of com.thesoftwareguild.sampleclass.55f96302
– This is the object’s hashcode.
What is a hashcode?
There are some things you need to know before we talk about what a hashCode is:
- The
equals()
method works withhashCode()
to make sure that two objects actually match. - If you are writing your own
equals()
, you are including logic that determines if two objects are indeed equal. What makes 2 objects equal? Same IDs? Same values? Something else? Theequals()
method should be written with that logic. - If you are creating your own
equals()
, you need to create your ownhashCode()
.
How are equals()
and hashCode()
used?
- Collections call
equals()
under the covers when they check for an object – such as checking to see if a collectioncontains()
an object or callingremove()
to take an object out of the collection. hashCode()
is used when adding objects toHashTable
,HashMap
, andHashSet
collections.- With these
Hash...
collections, the objects are stored by key. The hashcode is calculated on this key and used to determine where to store an object. When you try to search for an object on aHash...
collection, it uses thehashCode()
to locate the object. After it uses thehashCode()
to find the object or multiple objects (if multiple objects have the same hashcode), it runs through its results and usesequals()
to find the right key. - If items are equal, they should have the same hashcodes.
So hashCodes are addresses for objects that live in Hash… collections.
One man’s garbage may actually be that man’s treasure, once you understand what that garbage is. Hopefully, this demystified the “garbage” a little.