- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to create a HashSet in Java?
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.
The following is an example to create a HashSet.
Declare a HashSet object
HashSet hs = new HashSet();
Now, add some elements
hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); hs.add("K");
Now display the HashSet elements as shown below
Example
import java.util.*; public class Demo { public static void main(String args[]) { // create a hash set HashSet hs = new HashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); hs.add("K"); hs.add("M"); hs.add("N"); System.out.println(hs); } }
Output
[A, B, C, D, E, F, K, M, N]
- Related Articles
- How to sort HashSet in Java
- HashSet in Java
- How can we implement a Custom HashSet in Java?
- Traverse through a HashSet in Java
- Convert array to HashSet in Java
- Add elements to HashSet in Java
- Convert HashSet to TreeSet in Java
- The HashSet in Java
- Initializing HashSet in Java
- Initialize HashSet in Java
- Convert elements in a HashSet to an array in Java
- Convert an ArrayList to HashSet in Java
- Create HashSet from another collection in C#
- Importance of HashSet in Java
- Remove all elements from a HashSet in Java

Advertisements