A HashSet only stores values ones, when the equals method says that they're the same. Thats what I thought.
But now i'm adding Elements to a HashSet where the equals method returns true and the size of the set still grows?? sorry I'm confused. Some hints where i'm wrong would be nice.
Element t1 = new Element(false, false, false, false);
Element t2 = new Element(true, true, true, true);
Element t3 = new Element(false, false, false, false);
if (t1.equals(t3))
System.out.println("they're equal");
Set<Element> set = new HashSet<>();
set.add(t1);
set.add(t2);
set.add(t3);
System.out.println("set size: " + set.size());
so in this example my console output is:
they're equal
set size: 3
That makes no sense to me.. shouldn the size be 2?
If you have your own model classes you need to change some basic functions work like done in the below example.
Execution code :
Model Class :
Hope this helps.
The problem is that your
Element
class has not overridden theequals
andhashCode
methods or these implementations are broken.From
Object#equals
method javadoc:From
Object#hashCode
method javadoc:Make sure the implementations of these methods satisfy these rules and your
Set
(backed by aHashSet
) will work as expected.Yes We Can implement it with the object of the classes which are not FINAL.
HashSet Checks for two methods
hashCode()
andequals()
before adding any Object. First it checks for the methodhashCode()
,if it returns the hashcode which is same with any of the object in Set, then it checks for the equals method for that object,which internally compares the references for both objects i.ethis.obj1==obj
.If these are the same references in that case it returns true means it is a duplicate value. We can add duplicate non-final objects by overriding HashCode and equals method. In HashCode() you can return same hashcode in case of same parameters.See example:
The output will be 1.
P.S:Without overriding these methods,output will be 3 since it will use their default behavior.
Your objects have different hashes so HashSet "puts" then in different "buckets".