- 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
Initializing HashSet in Java
HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.
A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.
Following is an example to initialize a HashSet with string elements −
Example
import java.util.*; public class Main { public static void main(String[] args) { String str[] = { "Tom", "Jack", "Katie", "Tim" }; Set<Integer> set = new HashSet(Arrays.asList(str)); System.out.println("HashSet elements = "+set); } }
Output
HashSet elements = [Tom, Katie, Tim, Jack]
Let us see another example −
Example
import java.util.*; public class Main { public static void main(String args[]) { Set<String> hashSet = new HashSet<String>(); hashSet.add("green"); hashSet.add("blue"); hashSet.add("red"); hashSet.add("cyan"); hashSet.add("orange"); hashSet.add("green"); System.out.println("HashSet elements
"+ hashSet); Set<String> treeSet = new TreeSet<String>(hashSet); System.out.println("Sorted elements
"+ treeSet); } }
Output
HashSet elements [red, orange, green, blue, cyan] Sorted elements [blue, cyan, green, orange, red]
- Related Articles
- Initializing HashSet in C#
- Initializing a List in Java
- HashSet in Java
- Initialize HashSet in Java
- The HashSet in Java
- Importance of HashSet in Java
- Convert HashSet to TreeSet in Java
- How to sort HashSet in Java
- Traverse through a HashSet in Java
- Get size of HashSet in Java
- Convert array to HashSet in Java
- Add elements to HashSet in Java
- Get Enumeration over HashSet in Java
- Remove duplicate elements in Java with HashSet
- Difference between ArrayList and HashSet in Java

Advertisements