1) HashSet doesn’t maintain any kind of order of its elements.
2) TreeSet sorts the elements in ascending order.
3) LinkedHashSet maintains the insertion order. Elements gets sorted in the same sequence in which they have been added to the Set.
See Example :
import java.util.LinkedHashSet;
public class Example1 {
public static void main(String[] args) {
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
// Adding elements of String type to the LinkedHashSet
linkedHashSet.add("Linke 3");
linkedHashSet.add("Linke 1");
linkedHashSet.add("Linke 5");
linkedHashSet.add("Linke 2");
linkedHashSet.add("Linke 4");
linkedHashSet.add("Linke 6");
System.out.println(linkedHashSet);
// LinkedHashSet of Integer Type
LinkedHashSet<Integer> LinkedSetNum = new LinkedHashSet<Integer>();
// Adding elements
LinkedSetNum.add(14);
LinkedSetNum.add(23);
LinkedSetNum.add(11);
LinkedSetNum.add(62);
LinkedSetNum.add(81);
LinkedSetNum.add(33);
System.out.println(LinkedSetNum);
}
}
//see result
[Linke 3, Linke 1, Linke 5, Linke 2, Linke 4, Linke 6]
[14, 23, 11, 62, 81, 33]
we saw the result as the put in, put out , Both type of LinkedHashSet have preserved the insertion order.
EmoticonEmoticon