Java Reference
In-Depth Information
// Add a few more elements
s2.add("Ellen");
s2.add("Sara");
s2.add(null); // one null is fine
s2.add(null); // Duplicate!!! No effect
// Print the sets
System.out.println("s1: " + s1);
System.out.println("s1.size(): " + s1.size());
System.out.println("s2: " + s2);
System.out.println("s2.size(): " + s2.size());
}
}
s1: [Donna, Ken, John]
s1.size(): 3
s2: [null, Ellen, Donna, Ken, John, Sara]
s2.size(): 6
The Collections Framework offers the LinkedHashSet class as another implementation class for the Set interface.
The class adds one feature over the HashSet implementation. The HashSet implementation does not guarantee the
ordering of elements during iteration. The LinkedHashSet implementation guarantees that the iterator of a Set will
return the elements in the same order the elements were inserted (insertion order).
I will discuss maintaining ordering of elements in a Set in the next section when I discuss SortedSet . The
LinkedHashSet class provides insertion ordering without incurring any overhead.
Listing 12-6 compares the use of HashSet and LinkedHashSet classes. The output shows that HashSet does not
maintain any ordering on the elements whereas the LinkedHashSet maintains the insertion order.
Listing 12-6. Comparing the HashSet and LinkedHashSet Implementations of the Set Interface
// LinkedHashSetTest.java
package com.jdojo.collections;
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.HashSet;
public class LinkedHashSetTest {
public static void main(String[] args) {
Set<String> s1 = new LinkedHashSet<>();
s1.add("John");
s1.add("Adam");
s1.add("Eve");
s1.add("Donna");
System.out.println("LinkedHashSet: " + s1);
// Add the same elements to this set
Set<String> s2 = new HashSet<>();
s2.add("John");
s2.add("Adam");
 
Search WWH ::




Custom Search