Problem statement: what do you mean by LinkedHashSet in collection?
- LinkedHashSet is the child class of HashSet
- Introduced in 1.4 version
- LinkedHashSet is exactly same as HashSet except the following difference
- HashSet:
- The underlying data structure is Hashtable
- Insertion order is not preserved
- Introduced in 1.2 version
- LinkedHashSet:
- The underlying data structure is Hash table + Linked List(this is hybrid data structure)
- Insertion order is preserved
- Introduced in 1.4 version
For example:-
- HashSet:
- import java.util.HashSet;
- public class HashSetExe {
- public static void main(String[] args) {
- HashSet h = new HashSet();
- h.add("B");
- h.add("C");
- h.add("D");
- h.add("Z");
- h.add("null");
- h.add("10");
- System.out.println(h.add("z"));
- System.out.println(h.add("Z"));
- System.out.println(h);
- }
- }
Output:
true
false
[B, C, D, null, Z, z, 10]
Note: Here, insertion order is not preserved in HashSet
true
false
[B, C, D, null, Z, z, 10]
Note: Here, insertion order is not preserved in HashSet
- LinkedHashSet:
- import java.util.LinkedHashSet;
- public class LinkedHashSetExe {
- public static void main(String[] args) {
- LinkedHashSet h = new LinkedHashSet();
- h.add("B");
- h.add("C");
- h.add("D");
- h.add("Z");
- h.add("null");
- h.add("10");
- System.out.println(h.add("z"));
- System.out.println(h.add("Z"));
- System.out.println(h);
- }
- }
Output:
true
false
[B, C, D, Z, null, 10, z]
Note: Here, insertion order is preserved in LinkedHashSet
- LinkedHashSet is the best choice to develop cache based applications, where duplicates are not allowed and insertion order must be preserved.
No comments:
Post a Comment