Hello coders, today I am going to talk about another class that implements the Set interface in Java called LinkedHashSet.
Points to Notice
1. Contains Unique Values (Like HashSets)
LinkedHashSets also contain unique values. If we try to duplicate a value, the existing value gets overwritten by the new value.
//Creating a LinkedHashSet LinkedHashSet<String> myLinkedHashSet = new LinkedHashSet<>(); //Adding Elements myLinkedHashSet.add("Joey"); myLinkedHashSet.add("Chandler"); myLinkedHashSet.add("Ross"); myLinkedHashSet.add("Monica"); myLinkedHashSet.add("Chandler"); System.out.println(myLinkedHashSet);
Here is the console output.
[Joey, Chandler, Ross, Monica]
2. Allows null values (Like in HashSets)
//Creating a LinkedHashSet LinkedHashSet<String> myLinkedHashSet = new LinkedHashSet<>(); //Adding Elements myLinkedHashSet.add("Joey"); myLinkedHashSet.add("Chandler"); myLinkedHashSet.add(null); myLinkedHashSet.add("Ross"); myLinkedHashSet.add("Monica"); myLinkedHashSet.add("Chandler"); myLinkedHashSet.add(null); System.out.println(myLinkedHashSet);
Here is the console output.
[Joey, Chandler, null, Ross, Monica]
3. Saves values according to the Insertion Order
The LinkedHashSet saves values according to the order we add them. This makes it stand out from the HashSet class.
//Creating a LinkedHashSet LinkedHashSet<String> myLinkedHashSet = new LinkedHashSet<>(); //Adding Elements myLinkedHashSet.add("Joey"); myLinkedHashSet.add("Chandler"); myLinkedHashSet.add(null); myLinkedHashSet.add("Ross"); myLinkedHashSet.add("Monica"); myLinkedHashSet.add(null); myLinkedHashSet.add("The Ugly Naked Man"); myLinkedHashSet.add("Ursula"); myLinkedHashSet.add("Emily"); System.out.println(myLinkedHashSet);
Here is the console output.
[Joey, Chandler, null, Ross, Monica, The Ugly Naked Man, Ursula, Emily]
4. Non-synchronized
Methods
LinkedHashSet class implements all the methods that are being used in HashSets. You can take a look at my HashSet article to read and learn about them.
Besides, I always recommend you to read the Java documentation for further details. Here is the link to LinkedHashSet class documentation.
Thank you for reading the article. I hope you got a good understanding of LinkedHashSets. If you liked it, drop a like and follow my blog. Stay Safe ✌