Hi,
I am using jdk1.4.2.
I am using HashSet, and seem, it allows me to add duplicate values.
HashSet implements Set interface,
and in Set interface javadoc, it is clearly written that
"A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2)"
Similiar thing is written for add() javadoc.
My code snippet is as follows:-
--------------------------------------------------------------
import java.util.HashSet;
public class TestHashSet
{
public static void main(
String arg[])
{
HashSet set = new HashSet();
set.add(new Inner(1));
set.add(new Inner(1));
set.add(new Inner(1));
System.out.println(set.size());
}
}
class Inner
{
private int i=0;
public Inner(int _i)
{
i=_i;
}
public boolean equals(Object o)
{
Inner inner = (Inner)o;
if(inner.i==this.i)
{
return true;
}
else
{
return false;
}
}
/* public int hashCode()
{
return i*1000;
} */
}
-------------------------------------------------------------
This code returns me size as 3.
If i uncomment hasCode() method,
it correctly prints me size as 1.
But, i believe, it should be using only equals() method to check duplication, and not hashCode()
After looking into implementation of HashSet class, found that it uses HashMap to store values.
I am wondering, where i am going wrong?
Please suggest.
thanks,
Anuj