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– 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:
equals()method works with
hashCode()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? The
equals()method should be written with that logic.
- If you are creating your own
equals(), you need to create your own
- Collections call
equals()under the covers when they check for an object – such as checking to see if a collection
contains()an object or calling
remove()to take an object out of the collection.
hashCode()is used when adding objects to
- 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 a
Hash...collection, it uses the
hashCode()to locate the object. After it uses the
hashCode()to find the object or multiple objects (if multiple objects have the same hashcode), it runs through its results and uses
equals()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.