Last Updated: 22 January, 2023
HashSet and HashMap are both important Collection Framework classes that can be found in the java.util package. There are the following differences between them:
The HashSet class is a member of the Java Collection Framework. HashSet was introduced in the JDK 1.2 version and is available in the java.util package.
A HashSet is used to create an unordered collection of elements that contains only unique elements; no duplicate elements are allowed. The HashSet provides constant-time performance for general operations such as add, remove, contain, size, etc.
HashSet's internal implementation is based on the hash table for creating and storing a collection of unique elements.
Java HashSet Class Declaration
Here, E defines the type of elements that the Set will contain.
Java HashSet important features:
The HashMap class was introduced in the Java 1.2 version and is available in the java.util package. HashMap is a child class of the AbstractMap class, and it implements the Map interface as well as the Cloneable and Serializable interfaces.
HashMap is used to store the data in the form of key-value pairs, where keys must be unique and values may be duplicated. HashMap accepts only one null key and multiple null values.
Java HashMap Class Declaration
Here, K is the key Object type and V is the value Object type.
Java HashMap important features:
HashSet | HashMap |
---|---|
HashSet implements the Set interface. | HashMap implements the Map interface. |
HashSet is an unordered collection of elements that contains only unique elements. | HashMap stores elements in the form of key and value pairs and, keys must be unique. If the key is duplicated then the old key is replaced with the new value. |
HashSet implements Set, Cloneable, Serializable, Iterable and Collection interfaces. | HashMap implements Map, Cloneable, and Serializable interfaces. |
HashSet requires just one parameter for its object initialization. | HashMap requires two parameters (key and value) for its object initialization. |
HashSet can contain a single null value. | HashMap can contain a single null key and no restriction on any number of null values. |
For additing the element we use add() method. | Here, we use the put() method for adding an element. |
HashSet internally uses the HashMap object to store or add objects. | HashMap internally uses hashing to store or add objects. |
HashSet performance is slower than HashMap. | HashMap performance is faster than HashSet. |
Output
HashSet elements: [800, null, 500, 200]
Output
Iterating Hashmap and printing Key and Value
in - India
en - England
us - United State
ca - Canada
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com