
Here's how the HashSet works. It maintains an array of buckets. When an object is inserted, it finds the appropriate bucket corresponding to the objects HashCode. Then it calls the equals method to compare the equality of objects in the bucket.If an equals returns true with any object of the bucket then the new object is not inserted.
Now Here's the situation. There's a class A. Its equals and hashcode method is overridden. equals always returns false and hashcode always returns a single value say 5.
Here's my code.
import java.util.*; public class Prac {
@Override
public int hashCode() {
return 10;
}
@Override
public boolean equals(Object obj) {
return false;
}
public static void main(String args[]) {
HashSet<Prac> hs=new HashSet<Prac>();
Prac p=new Prac();
hs.add(p);
p=new Prac();
hs.add(p);
p=new Prac();
hs.add(p);
System.out.println(hs.size());
}
}
The output is 3. If I do re-initialize p using p= new Prac() after the first insertion then only once the insertion will take place and the output is 1.
The point is, the hashcode is same and the equals always returns false, so if hs.add(p) is called again without re-initializing variable p, then it should insert the object again. Can anyone tell me the concept behind this??

In your code, HashSet stores the values of Prac type as you have specified:
HashSet<Prac> hs=new HashSet<Prac>();
So, while adding the object of Prac using add method of hashset, it get stored into hastset.And you have created 3 objects of Prac and stored all of them into same hashset.So it returns 3 when you called size() method of HashSet.
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.