pankaj
pankaj

Reputation: 1733

what should be used HashMap or HashSet?

If you are given a set of records (say, User records with Id, Name and age fields) and you need to send a collection of it to the view for simple traversal. Then which collection would be preferable for use between HashMap and HashSet and why? What hashcode generation code would you use in the User class for efficiency?

Upvotes: 0

Views: 1294

Answers (2)

Arun Kumar
Arun Kumar

Reputation: 6794

HashMap and HahSet use diffrent data structure to store objects.

In a HashMap you store objects in key-value pairs

In a HashSet you store only the keys as objects.


Following are some of the difference between them:


  1. HashSet is implementation of Set interface. HashMap is the implementation of Map interface.
  2. HashSet Store only value. HashMap Stores data in form of key value pair.
  3. HashSet does not allow duplicate values/objects HashMap allows duplicate value/objects but would not allow duplicate key.
  4. HashSet is slower than hashmap. HashMap is faster than hashset because the values are associated to unique key
  5. In HashSet, 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.In HashMap, hashcode value is calculated using key object.

Upvotes: 1

npinti
npinti

Reputation: 52185

A HashSet is in itself an implementation of the HashMap so in the end it does not really make much of a difference. However, since you are dealing with users, I think that eventually you will need to access User objects by ID.

Assuming that each user has a unique ID, you could use a HashMap with ID's as a key and the entire User object as value. This will allow you to both traverse and access specific user data.

Upvotes: 1

Related Questions