LinkedHashSet in Java is also one of the implementation of the Set interface like HashSet and Treeset. How LinkedHashSet differs from the other implementation HashSet is that unlike HashSet which is unordered, LinkedHashSet is an ordered collection, it maintains iteration ordering, which is the order in which elements were inserted into the set.
LinkedHashSet implementation in Java
LinkedHashSet maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering. LinkedHashSet class in Java extends HashSet apart from implementing Set interface and uses the methods of the HashSet class itself.
If you have idea about the HashSet internal implementation then you must be knowing that internally HashSet uses HashMap to store its element. Same way LinkedHashSet internally uses LinkedHashMap.
Features of LinkedHashSet
Some of the features of the LinkedHashSet which are discussed in this post are as follows-
- LinkedHashSet in Java stores only unique elements.
- LinkedHashSet is an ordered collection and maintains the insertion order.
- LinkedHashSet permits null elements.
- LinkedHashSet is not thread-safe.
- The iterators returned by the iterator method of the LinkedHashSet class are fail-fast. Which means, if the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException.
Java LinkedHashSet constructors
LinkedHashSet class in Java has 4 constructors.
- LinkedHashSet()- Constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
- LinkedHashSet(int initialCapacity)- Constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).
- LinkedHashSet(int initialCapacity, float loadFactor)- Constructs a new, empty linked hash set with the specified initial capacity and load factor.
- LinkedHashSet(Collection<? extends E> c)- Constructs a new linked hash set with the same elements as the specified collection.
Java example creating a LinkedHashSet
This example shows how LinkedHashSet is created and elements added to it.
import java.util.LinkedHashSet; import java.util.Set; public class LinkedHashSetDemo { public static void main(String[] args) { // Creating LinkedHashSet Set<String> carSet = new LinkedHashSet<String>(); // Storing elements carSet.add("Audi"); carSet.add("BMW"); carSet.add("Mini Cooper"); carSet.add(null); carSet.add("Jaguar"); carSet.add("Mini Cooper"); carSet.add(null); // Iterating the Set for(String str : carSet){ System.out.println("Car Name- " + str); } } }Output
Car Name- Audi Car Name- BMW Car Name- Mini Cooper Car Name- null Car Name- Jaguar
As you can see from the output insertion order is maintained. Also duplicate element is added only once and it doesn’t affect the insertion order, same way null is added only once even if it is added more than once.
LinkedHashSet implementation is not synchronized
LinkedHashSet in Java is not thread safe as it is not synchronized. If multiple threads access a LinkedHashSet concurrently, and at least one of the threads modifies the set structurally, it must be synchronized externally. You can wrap your LinkedHashSet using the Collections.synchronizedSet method.
Set s = Collections.synchronizedSet(new LinkedHashSet(...));
Java LinkedHashSet iterator
The iterators returned by LinkedHashSet's collection view methods are fail-fast. If the set is modified at any time after the iterator is created, in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException.
Iterating LinkedHashSet Java examplepublic class LinkedHashSetDemo { public static void main(String[] args) { Set<String> carSet = new LinkedHashSet<String>(); // Storing elements carSet.add("Audi"); carSet.add("BMW"); carSet.add("Mini Cooper"); carSet.add("Jaguar"); Iterator<String> itr = carSet.iterator(); while(itr.hasNext()){ System.out.println("Car Name- " + itr.next()); } } }Output
Car Name- Audi Car Name- BMW Car Name- Mini Cooper Car Name- Jaguar
Performance of LinkedHashSet
Like HashSet, LinkedHashSet provides constant-time performance for the basic operations (add, contains and remove), assuming the hash function disperses elements properly among the buckets. Though performance wise LinkedHashSet is likely to be just slightly below that of HashSet, due to the added expense of maintaining the linked list. One exception is iteration that is faster in LinkedHashSet because of the linked list implementation.
Reference: https://docs.oracle.com/javase/10/docs/api/java/util/LinkedHashSet.htmlThat's all for the topic Java LinkedHashSet With Examples. If something is missing or you have something to share about the topic please write a comment.
You may also like
- HashSet Vs LinkedHashSet Vs TreeSet in Java
- HashMap Internal Implementation in Java
- How to Sort ArrayList of Objects in Java
- Life Cycle of a Thread (Thread States) in Java
- How to Create Custom Exception Class in Java
- How to Convert String to Byte Array in Java
- Search String in Another String in Java - indexOf, lastIndexOf, contains methods
- fnmatch Module in Python - File Name Pattern Matching
No comments:
Post a Comment