Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a set allow duplicates?

Tags:

java

set

So this is more of an "trying to understand" question, than a "I need a solution" question. For an assignment we were ask to create a List of products that have an itemNumber and a price, but only one of each, so no item with the same itemNumber. I figured I could create a set and that would get rid of the duplicates problem. But if I add a producta 1 , 4.99 and a productb 1 , 2.99 , both products are added.

Does that mean, that the set determines these products to be different b/c they have a different price and therefore can be added to the set?

like image 959
Nik Rawlins Avatar asked Dec 23 '22 21:12

Nik Rawlins


2 Answers

Assuming you are using a form of java.util.Set. Sets in java use the equals method to compare two objects. You want to override the equals method for the class that you wish to compare (Product) to tell the set that they are equal when the item numbers match.

https://docs.oracle.com/javase/7/docs/api/java/util/Set.html

Edit: As 911DidBush and Todd Sewell mentioned, whenever you override the equals method you will also want to override the hashCode method as to not break the contract of hashCode.
From the Java doc:

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes.

http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

like image 191
Sore Throat Avatar answered Dec 26 '22 12:12

Sore Throat


A quote from the Set javadoc:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.

As you can see, whether or not two objects are considered the same is determined by calling the accordingly named equals method. Keep in mind that when you implement equals you should also implement hashcode, as explained here and in the equals javadoc.

like image 32
Todd Sewell Avatar answered Dec 26 '22 11:12

Todd Sewell