Clavin June
Aug 11 · 2 min read

I’ll tell you how to make java Set class works for user-defined class, and save your time to eliminate duplicate objects.

Set Class

Set is collection in java which has no duplicate values. It determines the duplicate objects by using equals function. Equals function will returns true on wrapper class for primitive data types if they have a same value, but they will returns false on user-defined classes. Hmm, sounds like a problem to me.

Let’s type some code

Let’s say we have a book transactions and then we want to know what books bought today. The case is we want to select the book distinctly using java although we can use database query because it’s the title of this article LOL.

Remove duplicate objects with set

The code above won’t work because even though the books has a same title, author, etc they’re still different on code. Our job is to override the equals function on Book Class so Set class will work properly.

hashCode()

We’re gonna override hashCode function so we can use the equality of hashCode on the equals function.

Simple hash generator
Overridden equals and hashCode function

Conclusion

Our hashCode function will returns a generated number from book’s author, title, and edition and our equals function will use the number for equation. So java will think books with the same author, title, and edition is the same book and it will make Set eliminates duplicate books as we want.

Thank you for reading!


Faun

The Must-Read Publication for Aspiring Developers & DevOps Enthusiasts

Clavin June

Written by

a bunch of perceptrons

Faun

Faun

The Must-Read Publication for Aspiring Developers & DevOps Enthusiasts

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade