In this chapter you will learn:
- What is LinkedHashSet Class in Java
- Declaration and Methods of LinkedHashSet Class
- Programming Example
What is LinkedHashSet Class in Java?
LinkedHashSet is an implementation of HashSet in a linked list with predictable iteration order. It is different from HashSet as it maintains doubly linked list through its all entries. Linked list maintain the insertion order so the items are stored in Linked Hash Table as the order they inserted. It inherits all the methods of set operation and allow null element entry.
Constructors
Constructors | Descriptions |
LinkedHashSet() |
Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75). |
LinkedHashSet(Collection<? |
Constructs a new linked hash set with the same elements as the specified collection. |
LinkedHashSet(int initialCapacity) |
Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75). |
LinkedHashSet(int initialCapacity, |
Constructs a new, empty linked hash set with the specified initial capacity and load factor. |
Methods Inherited From Class
Class | Methods |
java.util.HashSet |
add(), clear(), clone(), contains(), isEmpty(), iterator(), remove(), size() |
java.util.AbstractSet |
equals(), hashCode(), removeAll() |
java.util.AbstractCollection |
addAll(), containsAll(), retainAll(), toArray(), toArray(), toString() |
java.lang.Object |
finalize(), getClass(), notify(), notifyAll(), wait(), wait(), wait() |
java.util.Set |
add(), addAll(), clear(), contains(), containsAll(), equals(), hashCode(), isEmpty(), iterator(), remove(), removeAll(), retainAll(), size(), toArray(), toArray() |
Declaration:
LinkedHashSeths=new LinkedHashSet ();
Programming Example
import java.util.*; class LinkedHashSet_Example { public static void main(String[] args) { //Declaring LinkedHashSet LinkedHashSeths=new LinkedHashSet (); //Adding Item hs.add("C#"); hs.add("Java"); hs.add("SQL"); hs.add("PHP"); hs.add("HTML"); //Printing LinkedHashSet Iterator itr=hs.iterator(); while(itr.hasNext()) { System.out.print(itr.next() + " "); } //Removing an Item System.out.println("\nItem Removed : "+ hs.remove("SQL")); //Printing System.out.println(hs); } }
Output
D:\JavaProgram>javac LinkedHashSet_Example.java
D:\JavaProgram>java LinkedHashSet_ExampleC# Java SQL PHP HTML
Item Removed : true
[C#, Java, PHP, HTML]
_
D:\JavaProgram>java LinkedHashSet_ExampleC# Java SQL PHP HTML
Item Removed : true
[C#, Java, PHP, HTML]
_
Summary
In this chapter you learned LinkedHashSet class in java with programming example. In the next chapter you will learn TreeSet Class in Java.