wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes add values to a  set and remove Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "add values to a  set and remove" Watch "add values to a  set and remove" New topic
Author

add values to a set and remove

Asanka Vithanage
Ranch Hand

Joined: Oct 24, 2008
Posts: 59
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





SCJP 1.5 (94%)
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
garima jain
Ranch Hand

Joined: Sep 22, 2008
Posts: 60
Ankit, whatever you have explained applies only to hashcode or it applies all classes/interfaces that implement/extend Set?
garima jain
Ranch Hand

Joined: Sep 22, 2008
Posts: 60
Sorry for the typo, it is HashSet and not hashcode.
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9313
    
  17

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...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: add values to a set and remove