when we add values to a set.what is actually happen .??? is it check hashcode vaue or equal method result or both. i try to find the method but i fail to find it following code gives [Key@1, Key@2] as out put plese can any body explain
and also when removing object from set what kind of pattern is it use
Yes Set uses both the hashCode and equals method. It uses hashCode method for doing fast processing. Suppose you add an object to the set, the hashCode of that object is 123, then the set will check if there is already an object with that hashCode in the set, if there is not, then the object is added to the set. If there is already 1 or more object with that hashCode in the set, then it will use equals method to check if the object is already in the set. If the object is already in the set, it is not added otherwise it is added in the set.
Same is the case when you use contains or remove method. Suppose you call remove method with an object. The Set will check if there is any object with the same hashCode as the object to be removed. If no object with the same hashCode is found, then no object will be removed. If one or more object is found with the same hashCode, then equals method will be used to find the exact object to be removed. If an exact match is found, then the object is removed otherwise no object is removed...
Garima it applies to hash based collections i.e. HashSet, LinkedHashSet, HashMap and LinkedHashMap (I am not sure about Hashtable). Sorted collections i.e. TreeSet and TreeMap depend on compare or compareTo method...