LinkedHashSet Class in Collection Framework

java.util.LinkedHashSet;
public class LinkedHashSet extends HashSet implements Set, Cloneable, java.io.Serializable
LinkedHashSet class provides the implementation of Set interface through HashSet class. A LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. Use this class instead of HashSet when you care about the iteration order. When you iterate through a HashSet the order is unpredictable, while a LinkedHashSet lets you iterate through the elements in the order in which they were inserted.
LinkedHashSet class features:
  1. It is an insertion ordered, unsorted set.
  2. It can not contain duplicate elements.
  3. It is unsynchronized.
  4. A LinkedHashSet can contain at most one null value.
  5. hashCode() and equals() methods is used for its elements .
  6. Data structure is based on Hash table and doubly-linked list.
To prevent unsynchronized access to the list:
Set set = Collections.synchronizedSet(new LinkedHashSet(…));
Constructor of LinkedHashSet
  1. public LinkedHashSet()
    It is used to create  an empty set with an initial capacity of 16 and load factor 0.75.
  2. public LinkedHashSet(Collection c)
              it is used to create a set containing the elements of the specified collection
  3. public LinkedHashSet(int initialCapacity)
             it is used to create an empty set with the specified initial capacity.
  4. public LinkedHashSet(int initialCapacity, float loadFactor)
Example of LinkedHashSet class
import java.util.LinkedHashSet; import java.util.Iterator; public class LinkedHashSetDemo{ public static void main(String[] args) { // LinkedHashSet Creation LinkedHashSet lhs = new LinkedHashSet(); // Adding elements to the LinkedHashSet lhs.add("101"); lhs.add("102"); lhs.add("103"); lhs.add("101"); lhs.add("104"); lhs.add("105"); lhs.add("103"); lhs.add("106"); // Display content of LinkedHashSet System.out.println("Content of lhs " + lhs); // Display content of LinkedHashSet using iterator Iterator it=lhs.iterator(); System.out.println("Content of LinkedHashSet using listIterator : "); while(it.hasNext()) { System.out.println(it.next()); } } }
Output
Content of lhs [101, 102, 103, 104, 105, 106]
Content of LinkedHashSet using listIterator :
101
102
103
104
105
106

Download this example
 



 

Latest Tutorial


Most Visited Tutorial