We will cover following points of Hashset in Java:
- Basics of Hashset in Java
- How to iterate through Hashset in Java
- Constructor and methods of Hashset in Java
Basics of Hashset in Java
- HashSet is a class which implements Set, Cloneable, and Serializable interface but not RandomAccess interface.
- HashSet used to store the different types of elements.
- HashSet stores the element in an unordered way.
- In HashSet, none of the methods are Synchronized.
- HashSet uses indexing representation to store the element.
- HashSet doesn’t allow the duplicate elements.
- HashSet elements can be accessed randomly.
- HashSet element can be accessed by using Iterator but it can’t be accessed by using ListIterator.
- We can have null in HashSet.
How to iterate Hashset in Java
import java.util.Iterator; import java.util.List; import java.util.Set; public class HashSetExample { public static void main(String[] args) { Set<String> setObject = new HashSet<>(); setObject.add("Nadeem"); setObject.add("Puneet"); setObject.add("Shyam"); setObject.add("Jagdish"); setObject.add("Aakash"); setObject.add("Nadeem");// duplicates are not allowed and it will not give any compilation error Iterator<String> it = setObject.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
Constructor and methods of HashSet in Java
HashSet has mainly four constructor:
- HashSet()
- HashSet(Collection c)
- HashSet(int initialCapacity)
- HashSet(int initialCapacity, float loadFactor, boolean dummyValue)
Learn more about collection in java
You must log in to post a comment.