• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

add values to a set and remove

 
Asanka Vithanage
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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



 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ankit, whatever you have explained applies only to hashcode or it applies all classes/interfaces that implement/extend Set?
 
garima jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry for the typo, it is HashSet and not hashcode.
 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic