Linked HashSet Example Java Program


Definition

HashSet uses a hash table. More specifically, it uses a java.util.HashMap to store the hashes and elements and to prevent duplicates. java.util.LinkedHashSet extends this by creating a doubly linked list that links all of the elements by their insertion order. This ensures that the iteration order over the set is predictable.

Syntax

LinkedHashSet Variable_name = new LinkedHashSet();

Linked HashSet Example Program

import java.util.LinkedHashSet;

public class LinkedHashSetDemo {
    public static void main(String a[]){
        LinkedHashSet lh = new LinkedHashSet();
        lh.add("Monday");
        lh.add("Tuesday");
        lh.add("Wednesday");
		lh.add("Thursday");
		lh.add("Friday");
		lh.add("Saturday");
		lh.add("Sunday");
        System.out.println(lh);
        System.out.println("Size of LinkedHashSet: "+lh.size());
        System.out.println("Is LinkedHashSet empty? : "+lh.isEmpty());
    }
}

Sample Output

Output is:
[first, second, third]
LinkedHashSet size: 7
Is LinkedHashSet empty? : false