LinkedHashSet Example in Java
Problem
A LinkedHashSet works like a HashSet — no duplicates, hash-based lookups — but it also threads a doubly-linked list through its entries, so iteration always follows insertion order instead of the unpredictable order a plain HashSet gives.
Add several elements to a LinkedHashSet, including a duplicate, and confirm iteration reflects the order they were first added in.
Java Program
import java.util.LinkedHashSet;
import java.util.Set;
public class LinkedHashSetExample {
public static void main(String[] args) {
Set<String> cities = new LinkedHashSet<>();
cities.add("Paris");
cities.add("Tokyo");
cities.add("London");
cities.add("Paris"); // already present — insertion order stays unchanged
for (String city : cities) {
System.out.println(city);
}
}
}Output
Core Logic
Every distinct element remembers the order it was first inserted in, so iterating the set later reproduces that same order exactly — the duplicate add() call doesn't move Paris or add a second entry.
- 1
add("Paris"),add("Tokyo"),add("London")insert three cities in that order. - 2
add("Paris")again has no effect — Paris is already present, so the set's size and its position in the iteration order both stay unchanged. - 3Internally, LinkedHashSet maintains a doubly-linked list connecting the entries in insertion order, alongside the hash table that gives fast
add()/contains(). - 4The for-each loop walks that linked list, printing Paris, Tokyo, London — the exact order the three distinct cities were first added.
Key Point: This is the key difference from plain HashSet — a HashSet gives no iteration-order guarantee at all, while LinkedHashSet guarantees insertion order, at the cost of a little extra memory for the linked list.
Why: add() and contains() still run in average-case constant time via the underlying hash table, and the extra doubly-linked list only adds a constant amount of bookkeeping per entry, not per lookup.