Sunday, June 3, 2018

LinkedHashSet

Problem statement: what do you mean by LinkedHashSet in collection?
  1. LinkedHashSet is the child class of HashSet
  2. Introduced in 1.4 version
  3. LinkedHashSet is exactly same as HashSet except the following difference
  • HashSet:
  1. The underlying data structure is Hashtable
  2. Insertion order is not preserved
  3. Introduced in 1.2 version
  • LinkedHashSet:
  1. The underlying data structure is Hash table + Linked List(this is hybrid data structure)
  2. Insertion order is preserved
  3. Introduced in 1.4 version
For example:-
  • HashSet:
  1. import java.util.HashSet;
  2. public class HashSetExe {
  3. public static void main(String[] args) {
  4. HashSet h = new HashSet();
  5. h.add("B");
  6. h.add("C");
  7. h.add("D");
  8. h.add("Z");
  9. h.add("null");
  10. h.add("10");
  11. System.out.println(h.add("z"));
  12. System.out.println(h.add("Z"));
  13. System.out.println(h);
  14. }
  15. }

Output:
true
false
[B, C, D, null, Z, z, 10]

Note: Here, insertion order is not preserved in HashSet

  • LinkedHashSet:
  1. import java.util.LinkedHashSet;
  2. public class LinkedHashSetExe {
  3. public static void main(String[] args) {
  4. LinkedHashSet h = new LinkedHashSet();
  5. h.add("B");
  6. h.add("C");
  7. h.add("D");
  8. h.add("Z");
  9. h.add("null");
  10. h.add("10");
  11. System.out.println(h.add("z"));
  12. System.out.println(h.add("Z"));
  13. System.out.println(h);
  14. }
  15. }
Output:
true
false
[B, C, D, Z, null, 10, z]
Note: Here, insertion order is preserved in LinkedHashSet

  1. 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

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...