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 equa
Yes We Can implement it with the object of the classes which are not FINAL.
HashSet Checks for two methods hashCode()
and equals()
before adding any Object.
First it checks for the method hashCode()
,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.e this.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:
public class Product {
int i;
Product(int a)
{
this.i=a;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + i;
return result;
}
@Override
public boolean equals(Object obj) {
/*if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (i != other.i)
return false;
return true;*/
return true;
}
}
`
`
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
Product p1=new Product(1);
Product p2=new Product(1);
Product p3=new Product(1);
Set s=new HashSet();
s.add(p1);
s.add(p2);
s.add(p3);
System.out.println(s.size());
}
}
The output will be 1.
P.S:Without overriding these methods,output will be 3 since it will use their default behavior.