cancel
Showing results for 
Search instead for 
Did you mean: 

Set not working '-' as unique string

Former Member
0 Kudos

Hi ,

I had to use Set interface in java to identify unique strings in one of the scenarios . While developing the same I observed a weird behavior of Set that it was not accepting '-' to be unique and storing the value more than one time .

Does anyone has a proper explanation for why this can happen ?

Kind Regards,

Smriti Garg

Accepted Solutions (0)

Answers (1)

Answers (1)

Former Member
0 Kudos

What you're describing sounds odd, but since you didn't go into any details, let me answer with some very generic comments: Per definition of the [Set|http://download.oracle.com/javase/1.5.0/docs/api/java/util/Set.html] interface the objects within this collection are unique. I.e. if you check the method [add|http://download.oracle.com/javase/1.5.0/docs/api/java/util/Set.html#add%28E%29] for adding new elements you'll find the following comment:

Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element, o, to this set if this set contains no element e such that (o==null ? e==null : o.equals(e)). If this set already contains the specified element, the call leaves this set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.

So why could you have seemingly duplicate values in a Set? Assuming that you use some proper implementation that complies with the constraints defined in the Set interface the only obvious reasons that come to my mind are that you're using elements in the Set, which don't match your expectation on how the equals() method is implemented or you are possibly using mutable objects as elements (so you add elements that are then later changed and thus you end up with duplicates).

Now if you're using a proper Set implementation and for example String's (which are immutable) as elements you shouldn't encounter this problem. However, if you're using elements with a homegrown class type, which doesn't override the equals() method, you might find seemingly duplicate values as elements. I.e. the standard [Object.equals()|http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html#equals%28java.lang.Object%29] method checks for referential equality (and doesn't compare attribute values). So in that case, you'd fix it by implementing a proper equals() method for the class that you're putting into the set.