- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Add elements to HashSet in Java
First, create a HashSet −
HashSet hs = new HashSet();
Now, add some elements using the add() method. Set the elements as a parameter. Here, we have set string −
hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); hs.add("K"); hs.add("M");
The following is an example to add elements to a HashSet −
Example
import java.util.*; public class Demo { public static void main(String args[]) { 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
- Add all the elements from a collection to the HashSet in Java
- Iterate through elements of HashSet in Java
- Remove duplicate elements in Java with HashSet
- Convert elements in a HashSet to an array in Java
- Remove all elements from a HashSet in Java
- Iterate over the elements of HashSet in Java
- Add element to HashSet in C#
- Copy all elements of Java HashSet to an Object Array
- Count the number of elements in a HashSet in Java
- Add elements to HashMap in Java
- HashSet in Java
- Add elements to LinkedHashMap collection in Java
- Add elements to a Vector in Java
- How to add elements in Java CopyOnWriteArrayList?
- How to add elements in Java ArrayBlockingQueue?

Advertisements