I’ll tell you how to make java Set class works for user-defined class, and save your time to eliminate duplicate objects.
Set is collection in java which has no duplicate values. It determines the duplicate objects by using
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.
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
equals function on
Book Class so Set class will work properly.
We’re gonna override
hashCode function so we can use the equality of hashCode on the
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!