NOTE
LinkedHashSet
Usage, constructor, fields, other methods, and summary of LinkedHashSet.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What It Is
2. How to Use It
public class LinkedHashSetTest
{
public static void main(String[] args)
{
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(1);
set.add(2);
set.remove(2);
System.out.println(set.contains(1));
System.out.println(set.contains(2));
System.out.println(set.contains(3));
}
}
3. Source Analysis
3.1. Constructor
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
// Implemented using LinkedHashMap
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
3.2. Fields
public class LinkedHashSet<E>
extends HashSet<E>// Extends HashSet, so its fields are the same as HashSet
implements Set<E>, Cloneable, java.io.Serializable
// HashSet
public class HashSet<E>
extends AbstractSet<E>
implements Set<E>, Cloneable, java.io.Serializable
{
private transient HashMap<E,Object> map;
// Placeholder used as the value
private static final Object PRESENT = new Object();
}
3.3. Other Methods
Same as LinkedHashMap.md.
4. Summary
It is implemented using LinkedHashMap underneath, with a newly created Object used as the value placeholder.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub