LinkedHashSet class is another implementation class for the Set interface.
LinkedHashSet class adds one feature over the HashSet implementation.
The HashSet implementation does not guarantee the ordering of elements during iteration.
LinkedHashSet maintains insertion order.
The following code 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.
import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; public class Main { public static void main(String[] args) { Set<String> s1 = new LinkedHashSet<>(); s1.add("XML"); s1.add("Adam"); s1.add("Eve"); s1.add("Json"); System.out.println("LinkedHashSet: " + s1); // Add the same elements to this set Set<String> s2 = new HashSet<>(); s2.add("XML"); s2.add("Adam"); s2.add("Eve"); s2.add("Json"); System.out.println("HashSet: " + s2); System.out.println("s1.equals(s2): " + s1.equals(s2)); }/*from www.j a va2s. c om*/ }