We will cover following points of LinkedHashset in Java:
- Basics of LinkedHashset in Java
- How to iterate through LinkedHashset in Java
- Constructor and methods of LinkedHashset in Java
Basics of LinkedHashset in Java
- LinkedHashSet is a class which extends HashSet class and implements Set, Cloneable, Serializable interface.
- LinkedHashSet doesn’t allow duplicate elements.
- It uses node representation to store the elements.
- We can have null in LinkedHashSet.
- It maintains insertion order.
- LinkedHashSet elements can be iterated through Iterator and for-each loop only, it can’t be accessed using ListIterator and Enumeration interface.
- LinkedHashSet methods are not synchronized.
How to iterate LinkedHashset in Java
- Using iterator
import java.util.LinkedHashSet; import java.util.Set; public class IterateLinkedHashSet { public static void main(String[] args) { Set linkedHashSetObj = new LinkedHashSet(); linkedHashSetObj.add("nadeem"); linkedHashSetObj.add("shyam"); linkedHashSetObj.add("puneet"); linkedHashSetObj.add("nadeem"); linkedHashSetObj.add("nadeem"); Iterator it = linkedHashSetObj.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }Nadeem Puneet Shyam
- Using for each
import java.util.Set; public class ForEachLinkedHashSet { public static void main(String[] args) { Set<String> linkedHashSetObj = new LinkedHashSet(); linkedHashSetObj.add("nadeem"); linkedHashSetObj.add("shyam"); linkedHashSetObj.add("puneet"); linkedHashSetObj.add("nadeem"); linkedHashSetObj.add("nadeem"); for (String str : linkedHashSetObj) { System.out.println(str); } } }Nadeem Puneet Shyam
Constructor and methods of LinkedHashSet in Java
LinkedHashSetin Java has mainly 2 constructor:
- LinkedHashSet()
- LinkedHashSet(Collection c)
- LinkedHashSet(int initialCapacity)
- LinkedHashSet(int initialCapacity, float loadFactor)
Learn more about collection in java
You must log in to post a comment.