Java LinkedHashSet
In Java, a LinkedHashSet
is a subclass of the HashSet
class that maintains the insertion order of elements. Like a HashSet
, a LinkedHashSet
is an implementation of the Set
interface, and provides the same operations as a HashSet
. However, a LinkedHashSet
provides additional operations that allow you to maintain the order of elements in which they were inserted.
When you add elements to a LinkedHashSet
, they are stored in the order in which they were inserted. When you iterate over a LinkedHashSet
, the elements are returned in the order in which they were inserted.
Here's an example of how to use a LinkedHashSet
in Java:
import java.util.LinkedHashSet; public class LinkedHashSetExample { public static void main(String[] args) { // Create a new LinkedHashSet LinkedHashSet<String> set = new LinkedHashSet<>(); // Add elements to the set set.add("apple"); set.add("banana"); set.add("cherry"); // Print the set System.out.println(set); // Add another element to the set set.add("banana"); // Print the set again System.out.println(set); } }
Output:
[apple, banana, cherry] [apple, banana, cherry]
In the example above, we have created a LinkedHashSet
of strings and added three elements to it. When we print the set, the elements are printed in the order in which they were added. We then add another element to the set, and when we print the set again, the order of elements is maintained, and the duplicate element is not added.