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.
You presumably need to implement
equals()andhashCode()forMyClass, otherwise it won’t properly check equality.