-3

I am a beginner in Java, so this may be a dumb question. Why we need hashSet in Java? I just learned that Java hashSet is actually implemented with HashMap. In my understanding, whenever we use hashSet, we can always use hashmap, so why we need hashSet in java?

Thanks

King Saber
  • 559
  • 6
  • 11
  • 8
    Because it implements `Set` and not `Map`? – vanza Mar 07 '14 at 01:35
  • "Java hashSet is actually implemented with HashMap"? from where did you learnt that? – ironwood Mar 07 '14 at 02:00
  • @Namalak Although I don't believe it is a JLS requirement (and it shouldn't be), it is indeed the case for Sun/Oracle JDK. It is stated in the Javadoc of HashSet: `This class implements the Set interface, backed by a hash table (actually a HashMap instance). `. In fact I always think it is a common sense to know HashSet is internally using a HashMap, while TreeSet using a TreeMap – Adrian Shum Mar 07 '14 at 02:03
  • Wow! That's a new point for me! Honestly, never thought that. Anyway I didn't vote you down King Saber. :) – ironwood Mar 07 '14 at 02:09

2 Answers2

1

You can google differences between HashMap and HashSet to understand more.

  • HashMap is an implementation of Map interface;
  • HashSet is an implementation of Set Interface;
  • HashMap stores data in form of key value pair;
  • HashSet stores only objects;
  • Put method is used to add element in map;
  • Add method is used to add element is Set;
  • In hash map hashcode value is calculated using key object.
  • Here member object is used for calculating hashcode value which can be same for two objects. So equal() method is used to check for equality: if it returns false, that means two objects are different.

Got the info from here.

Pom12
  • 7,622
  • 5
  • 50
  • 69
chinna_82
  • 6,353
  • 17
  • 79
  • 134
  • 1
    I doubt the statement of `HashMap is faster than HashSet`. Although extra level of method call is going to make it slower but it is not gotta be anything significant. – Adrian Shum Mar 07 '14 at 02:01
  • Could you give why you said that a hashMap is faster than a hashSet or some reference links? – nachokk Mar 07 '14 at 02:04
0

You can, and you can even further argue that why we need ArrayList because you can see an ArrayList as a map with an integer as index, then you can use an HashMap and use integer as key and then you don't really need List anymore.

There are specific purpose and semantic meaning for different data structure, for example, Set is a collection that will not allow duplicate. Map aimed for providing key-value lookup. If you only want a collection to store non-duplicated objects, why use a Map that is aimed for other purpose?

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131