posted 20 years ago
Hi,
I am trying to use java.util.HashSet for storing collection of non-duplicate values of my own custom class.
Here is the sample program which I tried.
Output:
hashcode called97
hashcode called98
hashcode called97
hashcode called98
hashcode called97
s = [a, a, a, 1, b, b]
The UsingSet class has a single field value and two UsingSet instances are equal if their values are equal.
I dont know how add() method works to compare objects. But from the above output the add() method is not using the overloaded equals method (the print statements are getting not printed) and it adds to set even if attribute value has the same value.
Overloading hashCode() method also doesn't seems to work.
I tried the same with java.util.TreeSet() by passing my own comparator to constructor and it works fine.
Is it not possible with HashSet()..?
But again, trying the same for Integer class (look at last two add statements and output) works fine and Integer instances considered as equal if their values are equal..
So I think this should be possible..
Can you please help me if anyone know how to implement this.
Thanks very much,
Raja.