Java HashSet
HashSet is a class in the Java Collections Framework that implements the Set interface.
It is used to store unique elements and is based on hashing.
import java.util.HashSet;
public class HelloWorld {
public static void main(String[] args) {
HashSet<String> languages = new HashSet<>();
languages.add("Java");
languages.add("Python");
languages.add("Java");
System.out.println(languages);
}
}The duplicate "Java" is not stored twice.
Main Characteristics of HashSet
A HashSet:
- Does not allow duplicate elements.
- Does not guarantee insertion order.
- Provides efficient average-case operations for adding, removing, and checking elements.
- Allows one null element.
- Uses hashing internally.
- Is not synchronized.
Creating a HashSet
HashSet<String> names = new HashSet<>();It is often better to use the interface type:
Set<String> names = new HashSet<>();Adding Elements
Use add():
Set<String> names = new HashSet<>();
names.add("Amit");
names.add("Rahul");
names.add("Priya");Duplicate Elements
names.add("Amit");
names.add("Amit");Only one "Amit" is stored.
We can verify this using size():
System.out.println(names.size());How Does HashSet Identify Duplicates?
HashSet uses hashing to organize its elements.
When an object is added, its hashCode() is used as part of locating the appropriate area for the element.
When multiple elements are candidates for the same area, equals() is used to determine whether they represent the same value.
Therefore, when creating custom classes for use in hash-based collections, equals() and hashCode() should be implemented consistently.
Example with a Custom Class
class Student {
private int id;
Student(int id) {
this.id = id;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return this.id == other.id;
}
@Override
public int hashCode() {
return Integer.hashCode(id);
}
}Now two Student objects with the same ID can be considered equal:
Set<Student> students = new HashSet<>();
students.add(new Student(101));
students.add(new Student(101));The Set can treat them as the same logical element.
HashSet Does Not Guarantee Order
Consider:
HashSet<String> names = new HashSet<>();
names.add("Java");
names.add("Python");
names.add("C++");
System.out.println(names);Do not assume that the output will always be:
[Java, Python, C++]The iteration order of a HashSet is not guaranteed.
If insertion order matters, use LinkedHashSet.
Allowing Null
HashSet permits one null element.
HashSet<String> names = new HashSet<>();
names.add("Java");
names.add(null);
names.add(null);
System.out.println(names);Only one null can be stored.
Checking an Element
if (names.contains("Java")) {
System.out.println("Java exists");
}Removing an Element
names.remove("Java");Checking Size
System.out.println(names.size());Iterating Through HashSet
for (String name : names) {
System.out.println(name);
}Remember that the iteration order should not be assumed.
Complete Example
import java.util.HashSet;
import java.util.Set;
public class HelloWorld {
public static void main(String[] args) {
Set<String> skills = new HashSet<>();
skills.add("Java");
skills.add("Spring");
skills.add("SQL");
skills.add("Java");
System.out.println("Skills: " + skills);
System.out.println("Contains Java: "
+ skills.contains("Java"));
skills.remove("SQL");
System.out.println("After removal: " + skills);
}
}HashSet Performance
For typical use, HashSet provides average constant-time performance for basic operations such as:
- add()
- remove()
- contains()
Actual performance depends on factors such as hashing quality, collisions, collection size, and implementation details.
HashSet vs ArrayList
| Feature | HashSet | ArrayList |
|---|---|---|
| Duplicate elements | Not allowed | Allowed |
| Index-based access | No | Yes |
| Ordering | No guaranteed order | Maintains list order |
| Main purpose | Unique elements | Ordered sequence |
| contains() | Generally efficient | Generally requires searching |
| Null | One null allowed | Multiple nulls allowed |
HashSet vs LinkedHashSet
| Feature | HashSet | LinkedHashSet |
|---|---|---|
| Duplicate elements | No | No |
| Insertion order | Not guaranteed | Maintained |
| Memory overhead | Generally lower | Generally higher |
| Main use | Unique values | Unique values + insertion order |
When Should You Use HashSet?
Use HashSet when:
- You need unique elements.
- Ordering is not important.
- You frequently need membership checks.
- You want a general-purpose hash-based Set.
Examples include:
- Unique user IDs
- Unique email addresses
- Unique product codes
- Unique tags
- Tracking already-processed values
Important Points
- HashSet implements Set.
Duplicate elements are ignored. HashSet does not guarantee iteration order. It permits one null. Hashing is used internally. equals() and hashCode() are important for custom objects. HashSet is not synchronized. It provides efficient average-case basic operations.
Key Takeaway
HashSet is a hash-based Set implementation designed for storing unique elements efficiently when a particular iteration order is not required.
See you in next page....🙂