HashSet extends AbstractSet and implements the Set interface. Internally the HashSet create a collection which uses hash table for storage, the hash table uses hashing mechanism to store data, the below things you should consider if you are planning to use HashSet
- The HashSet will not allow duplicate values it won’t give any error while adding instead of error it will just return boolean values
- There is no guarantee that whatever order you have stored you will get it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package com.kesyandstrokes.examples.hashset; import java.util.HashSet; import java.util.Set; public class HashSetExample { public static void main(String[] args) { Set<String> users = new HashSet<String>(); // add items to the list users.add("author1"); users.add("author2"); users.add("author3"); users.add("author4"); for (String author : users) { System.out.println(author); } } } |
Output :
1 2 3 4 | author2 author1 author4 author3 |