Anil Giri wrote:
I am not able to figure out, why is this TreeSet allowing duplicate entries. As is evident, persons with same name e.g. T1or T3 must be treated as equal.
Your comparator is not valid. If you read the JavaDoc on the Comparator, you will notice that your comparator must enforce "total ordering" which it does not. Here is an example of why it fails...
Let's say you have three items - A, B, and C. A & B has the same name, while C is different.
A is first added to the set. No problem. B is then added to the set. Duplicate. No allowed. No problem. C is then added. No problem. Everything works.
Let's change the order.
A is first added to the set. No problem. C is then added to the set. No problem. B is then added. Now... What happens?
1. If B is first compared to A. It will be found as a duplicate. No problem.
2. If B is first compared to C, then it will be sorted depending on the order. So...
2a. If both A and B are both greater than or less than C, then they will fall on the same side as C, causing A and B to be compared, and found as a duplicate. No problem.
2b. If A and B don't compare the same with C -- meaning one is greater than and one is less than C, then there is no reason to compare A and B... because how can A and B be equal? One is greater and one is less than C. The ordering is ACB or BCA.
Henry