Java LinkedHashSet

Java LinkedHashSet
Syntax:
java.lang.Object
     java.util.AbstractCollection
         java.util.AbstractSet
             java.util.HashSet
                 java.util.LinkedHashSet

  • Note: E - the type of elements maintained by this set
  • The LinkedHashSet class has no members of its own.
  • Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface. 
  • A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements.
  • The hash code is then used as the index at which the data associated with the key is stored. 
  • The transformation of the key into its hash code is performed automatically.
  • The LinkedHashSet does not allow duplicate elements and it does not maintain order.
  • The difference between them is...
    • HashSet doesn’t maintain any kind of order of its elements.
    • TreeSet sorts the elements in ascending order.
    • LinkedHashSet maintains the insertion order and Elements gets sorted in the same sequence in which they have been added to the Set.

Constructors:

  • HashSet( ): This constructor constructs a default HashSet.
  • HashSet(Collection c): This constructor initializes the hash set by using the elements of the collection c.
  • LinkedHashSet(int capacity): This constructor initializes the capacity of the linkedhashset to the given integer value capacity. The capacity grows automatically as elements are added to the HashSet.
  • LinkedHashSet(int capacity, float fillRatio): This constructor initializes both the capacity and the fill ratio (also called load capacity) of the hash set from its arguments.
Methods:
  • How to declare object of LinkedHashSet?
    • Syntax:
LinkedHashSet lhset = new LinkedHashSet();
    • Example:
//non-generic
LinkedHashSet hs = new LinkedHashSet();
//Integer type
LinkedHashSet lhset1 = new LinkedHashSet();
//String type
LinkedHashSet lhset2 = new LinkedHashSet();
  • How to add new elements in LinkedHashSet?
    • Syntax:
         object-name.add(string);
    • Example: 
         lhset1.add(99);
         lhset2.add("PQ");
  • How to display all elements from LinkedHashSet?
    • Example:
System.out.println(lhset1);
System.out.println(lhset2);

  • How to display all elements using iterator?
    • Example:
Iterator i=lhset1.iterator();  
while(i.hasNext())
{
System.out.println(i.next());
}
  • How to remove an element from LinkedHashSet?
    • Example:
lhset1.remove(99)
  • How to check given element is present or not?
    • Example:
System.out.println("Checking if 99 is present);
System.out.println(lhset1.contains(99));
  • How to get the size of LinkedHashSet?
    • Example:
lhset1.size()

Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form