-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

4
  • 8
    Because it implements Set and not Map? Commented Mar 7, 2014 at 1:35
  • "Java hashSet is actually implemented with HashMap"? from where did you learnt that? Commented Mar 7, 2014 at 2: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 Commented Mar 7, 2014 at 2:03
  • Wow! That's a new point for me! Honestly, never thought that. Anyway I didn't vote you down King Saber. :) Commented Mar 7, 2014 at 2:09

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Could you give why you said that a hashMap is faster than a hashSet or some reference links?
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?

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.