Reputation: 1709
The below is my code,
public class Myclass{
some code is here.
}
public static void main(String args[]){
Set<Myclass> set = new HashSet<Myclass>();
Myclass mc = new Myclass();
for(int i=0;i<2;i++){
set.add(mc);
}
System.out.println("size of set : "+set.size());
}
The above code is print the output 2 but it will be 1. Is there any wrong with my code, if so then please suggest me how to avoid adding duplicate entries in set. I have override the equals() in my Myclass class.
Please reply me as soon as possible.
Thank you.
Upvotes: 0
Views: 1108
Reputation: 14988
You presumably need to implement equals()
and hashCode()
for MyClass
, otherwise it won't properly check equality.
Upvotes: 4