Friday, 7 September 2018

                                                    what is the size of HashSet?
package govind;
import java.util.HashSet;
public class Employee {
private String name;
@Override
public int hashCode() {
return 35;
}
@Override
public boolean equals(Object obj) {
return true;
}
public static void main(String[] args) {
HashSet h1 =new HashSet<>();
Employee e1=new Employee();
Employee e2=new Employee();
e1.name="GovindBallabhKhan";
e2.name="JavaTechnology";
h1.add(e1);
h1.add(e2);
System.out.println("Size="+h1.size());
}
}
o/p:----------------------------
size=1
As equals method always return true and hashcode return constant as 35.So when you try to put e2 in HashSet, when it will check for equals method, it will always return true, so e2 won’t be added to HashSet

No comments:

Post a Comment