Menu
Topics Index
...
`

LinkedHashSetDemo - Java Example Program


LinkedHashSetDemo
import java.util.*;

class LinkedHashSetDemo
{
    public static void main(String arg[])
    {
        LinkedHashSet<String> lhs = new LinkedHashSet<String>(); // LINE A
        lhs.add("Anderson");
        lhs.add("Bharath");
        lhs.add("Cruse");
        lhs.add("Dinesh");
        System.out.println("Eements retrieved in the order they were inserted : ");
        System.out.println(lhs);
        lhs.remove("Bharath"); // LINE B
        lhs.add("Bhuwaneshwar"); // LINE C
        System.out.println("Set after removing Bharath and adding Bhuwaneshwar : ");
        System.out.println(lhs);
        Object[] names = lhs.toArray();
        System.out.println("Displaying elements in array format : "); // LINE D
        for (Object name : names)
        {
            System.out.print(name + ", ");
        }
        System.out.println();
        lhs.clear(); // LINE E
        System.out.println("Displaying empty set : ");
        System.out.println(lhs);    
    }
}
OUTPUT

Eements retrieved in the order they were inserted :
[Anderson, Bharath, Cruse, Dinesh]
Set after removing Bharath and adding Bhuwaneshwar :
[Anderson, Cruse, Dinesh, Bhuwaneshwar]
Displaying elements in array format :
Anderson, Cruse, Dinesh, Bhuwaneshwar,
Displaying empty set :
[]

DESCRIPTION

In the above program we demonstrated how LinkedHashSet works. At first at LINE A we have created a LinkedHashSet and added some names to it and displayed it and at LINE B we have removed Bharath from the set using remove method and added Bhuwaneshwar to the at set at LINE C using add method and displayed. At LINE D we have created an array of Objects using toArray method and displayed each element in the array. At LINE E we have cleared all the elements in the set using clear method and displayed the empty set.

THINGS TO TRY
  • Now create a LinkedHasSet of Integers and add numbers form 1 to 5
  • Create a clone for the set in the program using clone method. Use the sample code below.
    lhs.clone();
  • Check whether Bharath exits in the set using contains method. Use the sample code below.
    lhs.contains("Bharath");

© meritcampus 2019

All Rights Reserved.

Open In App