In this tutorial, we will learn about the Java LinkedHashSet class and its methods with the help of examples.
The LinkedHashSet class of the Java collections framework provides functionalities of both the hashtable and the linked list data structure.
LinkedHashSet class which is implemented in the collections framework is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. Let’s see how to create a set object using this class.
// Java Program to illustrate the LinkedHashset Class
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);
}
}
output:
[B, A, D, E, C, F]
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. |