HashSet in Java with Example




HashSets and hash tables 

  • Lists allow for ordered elements, but searching them is very slow.
  • Can speed up search tremendously if you dont care about ordering.
  • Hash tables let you do this. Drawback is that you have no control over how elements are ordered.
  • hashCode() computes integer (quickly) which corresponds to position in hash table.
  • Independent of other objects in table.

HashSet  Class 

  • Hashing can be used to implement several important data structures.
  • Simplest of these is HashSet
    • add elements with add(Object) method
    • contains(Object) is redefined to first look for duplicates.
    • if duplicate exists, Object is not added
  • What determines a duplicate?
    • careful here, must redefine both hashCode() and equals(Object)!

HashSet

  • Look HashSet Example
  • Play around with some additional methods.

 


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com