• Post Reply Bookmark Topic Watch Topic
  • New Topic

Question regarding HashSet  RSS feed

 
Khuzema Dharwala
Ranch Hand
Posts: 61
Java Linux Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was studying the internal working of HashSet, it internally uses HashMap to store the values as Key in HashMap, then why java introduces HashSet collection at all.

May be I am missing something here can anyone please explain this.
 
Anurag Verma
Ranch Hand
Posts: 170
Hibernate Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Map is a 2 dimentional data structure, set is single dimentional, need and use of both are different. Ofcourse hashset is based on hashmap, but if hashset was skipped, we would have to create a hashset every time we need it to achieve the behavior it provides.
 
salvin francis
Bartender
Posts: 1664
37
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Khuzema Dharwala wrote:...why java introduces HashSet collection at all...

First of all, you need to understand the difference between java.lang.Set and a java.lang.Map
Javadoc for a Set:
A collection that contains no duplicate elements


Javadoc for a Map:
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.


So, they are two different types of collections (Actually a Map isn't strictly collection, but lets not go there.).
One has only elements while the other has a key value pair.
Now, to use the Set collection, java has given 2 concrete classes (At least two that I am aware of )
TreeSet and HashSet.
The TreeSet gives natural ordering and the HashSet is simply a collection of Non-duplicate entries which are Not-ordered in any manner. It may be backed up internally by any kind of implementation, you need not worry about that.

Hope this helps


 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!