logo

Java - The LinkedHashSet Class


Show

This class extends HashSet but adds no members of its own.

LinkedHashSet maintains a linked list of the entries in the set, in the order in which they were inserted. This allows insertion-order iteration over the set.

That is, when cycling through a LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted.

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.

Following is the list of constructors supported by the LinkedHashSet.

Sr.No.Constructor & Description
1

HashSet( )

This constructor constructs a default HashSet.

2

HashSet(Collection c)

This constructor initializes the hash set by using the elements of the collection c.

3

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.

4

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.

Example

The following program illustrates several of the methods supported by LinkedHashSet:

import java.util.*;
public class HashSetDemo {

   public static void main(String args[]) {
      // create a hash set
      LinkedHashSet hs = new LinkedHashSet();
      
      // add elements to the hash set
      hs.add("B");
      hs.add("A");
      hs.add("D");
      hs.add("E");
      hs.add("C");
      hs.add("F");
      System.out.println(hs);
   }
}

This will produce the following result:

Output

[B, A, D, E, C, F]

Here at Intellinuts, we have created a complete Java tutorial for Beginners to get started in Java.