The collection framework in Java provides a variety of data structures for storing and manipulating data. LinkedHashSet
It is a special type that combines the characteristics of hash tables and linked lists, and is suitable for situations where the insertion order of elements needs to be maintained and uniqueness ensured. This blog will introduce it in detail LinkedHashSet
, including its concepts, features, usage methods and sample code, aiming to help beginners better understand and apply this collection type.
1. What is LinkedHashSet?
LinkedHashSet
It is a class in the Java collection framework. It inherits from HashSet
, so it has the lookup performance of a hash table, while using a linked list to maintain the insertion order of elements. This means LinkedHashSet
having the following two main properties:
- Order :
LinkedHashSet
The insertion order of elements is maintained, that is, the order in which elements are added to the collection is the order in which they are in the collection. - Uniqueness : Same
HashSet
as ,LinkedHashSet
ensuring the uniqueness of elements and not allowing duplicate elements.
Therefore, LinkedHashSet
it is an ideal choice for scenarios where unique elements need to be stored in insertion order.
2. Creation and initialization of LinkedHashSet
To create an LinkedHashSet
object, you need to initialize it using a constructor. Here are several initialization methods:
2.1. Default constructor
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>();
This will create an empty LinkedHashSet
object with an initial capacity of 16 and a load factor of 0.75. You can adjust these parameters as needed.
2.2. Specifying capacity and loading factors
int initialCapacity = 20;
float loadFactor = 0.5f;
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(initialCapacity, loadFactor);
By specifying the initial capacity and load factor, you can have more granular control LinkedHashSet
over the performance and memory footprint of .
2.3. Create from existing collection
You can also create one from an existing collection such as List
or to convert between different collection types:Set
LinkedHashSet
Set<String> existingSet = new HashSet<>(Arrays.asList("A", "B", "C"));
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<>(existingSet);
This will initialize the new one using elements from the existing collection LinkedHashSet
.
3. Basic operations: add, delete and query elements
LinkedHashSet
Common collection operations are provided, including adding, deleting, and querying elements. Here are some examples of basic operations:
3.1. Adding elements
Use add
the method to LinkedHashSet
add elements to :
linkedHashSet.add("D");
linkedHashSet.add("E");
3.2. Delete elements
Use remove
the method to remove elements LinkedHashSet
from :
linkedHashSet.remove("B");
3.3. Query whether an element exists
Use contains
the method to check if an element exists in LinkedHashSet
:
boolean containsC = linkedHashSet.contains("C");
4. Traverse LinkedHashSet
Iterating LinkedHashSet
over the elements in usually uses an iterator or an enhanced for loop. Here are examples of two traversal methods:
4.1. Traversing using iterators
Iterator<String> iterator = linkedHashSet.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
System.out.println(element);
}
4.2. Use enhanced for loop traversal
for (String element : linkedHashSet) {
System.out.println(element);
}
Regardless of the traversal method, LinkedHashSet
elements will be returned in the order in which they were inserted, thus maintaining order.
5. Performance considerations for LinkedHashSet
LinkedHashSet
The performance is HashSet
similar to , and the time complexity of finding elements is O(1), which is achieved through a hash table. But unlike HashSet
, LinkedHashSet
you also need to maintain the linked list structure, so adding and removing elements may be HashSet
slightly slower than . But usually, this performance loss is negligible.
It is important to note that LinkedHashSet
the initial capacity and load factor settings will affect performance. If the initial capacity is too small, it may lead to frequent capacity expansion operations and reduce performance. Reasonable selection of capacity and load factor can improve performance and reduce memory usage.
6. Precautions for use
LinkedHashSet
There are some things to consider when using :
LinkedHashSet
It is thread-unsafe. If used in a multi-threaded environment, thread synchronization issues need to be considered, or thread-safe collection classes should be consideredConcurrentLinkedHashSet
.LinkedHashSet
It is allowed to store annull
element, but it is generally recommended to avoidnull
storing as a valid element to avoid confusion and errors.- When using a custom object as
LinkedHashSet
an element, you need to implementhashCode()
the andequals()
methods correctly to ensure the uniqueness and correctness of the object in the collection. LinkedHashSet
The performance is usually very high, but when processing large amounts of data, attention should be paid to the setting of the load factor to avoid frequent expansion operations.
7. LinkedHashSet example
Let's demonstrate the usage scenario with some sample code LinkedHashSet
:
7.1. Storing student list
Suppose we want to store a list of students and make sure that each student's name is unique and in the order in which they were added. We can LinkedHashSet
do this using:
LinkedHashSet<String> studentNames = new LinkedHashSet<>();
studentNames.add("Alice");
studentNames.add("Bob");
studentNames.add("Charlie");
studentNames.add("Alice"); // 这个重复的元素将被忽略
for (String name : studentNames) {
System.out.println(name);
}
Output:
Alice
Bob
Charlie
7.2. Record website visit history
Suppose we want to record the history of user visits to the website and maintain the order of visits. We can use LinkedHashSet
to store these records:
LinkedHashSet<String> visitHistory = new LinkedHashSet<>();
visitHistory.add("Homepage");
visitHistory.add("About Us");
visitHistory.add("Products");
visitHistory.add("Contact Us");
for (String page : visitHistory) {
System.out.println("Visited: " + page);
}
Output:
Visited: Homepage
Visited: About Us
Visited: Products
Visited: Contact Us
8. More uses of LinkedHashSet
When using LinkedHashSet
, in addition to the basic operations, there are some more usage methods and techniques. Here are some of them:
8.1. Get the size of LinkedHashSet
You can use size()
the method to get LinkedHashSet
the number of elements in :
int size = linkedHashSet.size();
This can help you understand the size of your collection so you can take appropriate control and optimization when processing your data.
8.2. Determine whether LinkedHashSet is empty
Use isEmpty()
the method to check LinkedHashSet
if is empty, it will return if there are no elements in the collection, true
otherwise it will return false
:
boolean isEmpty = linkedHashSet.isEmpty();
This is useful when writing conditional logic to perform different actions based on whether a collection is empty.
8.3. Clear LinkedHashSet
If you need to clear LinkedHashSet
all elements in , you can use clear()
the method:
linkedHashSet.clear();
This will make the collection empty and all elements will be removed.
8.4. Copy LinkedHashSet
If you need to create a LinkedHashSet
copy, you can use the constructor or clone()
method:
LinkedHashSet<String> copySet = new LinkedHashSet<>(linkedHashSet);
// 或者
LinkedHashSet<String> copySet = (LinkedHashSet<String>) linkedHashSet.clone();
This will clone the original collection, allowing you to work on it without affecting the original collection.
8.5. Convert to array
You can LinkedHashSet
convert the elements in to an array for more flexibility with your data:
String[] array = linkedHashSet.toArray(new String[0]);
This will return an array containing the elements of the collection. You can also choose the type and size of the array according to your needs.
8.6. Comparing LinkedHashSets
To compare two LinkedHashSet
for equality, you can use equals()
the method. Two LinkedHashSet
are considered equal when they have the same elements and are arranged in the same order.
LinkedHashSet<String> set1 = new LinkedHashSet<>(Arrays.asList("苹果", "香蕉", "橙子"));
LinkedHashSet<String> set2 = new LinkedHashSet<>(Arrays.asList("苹果", "香蕉", "橙子"));
boolean isEqual = set1.equals(set2); // 返回 true
8.7. Removing elements using iterators
As mentioned above, using iterators can safely remove elements and avoid ConcurrentModificationException
exceptions.
Iterator<String> iterator = linkedHashSet.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("B")) {
iterator.remove(); // 安全删除元素
}
}
These more usage methods and techniques can help you process data in more flexibly LinkedHashSet
and meet different programming needs. Whether it's getting the size of a collection, clearing a collection, or creating a copy of a collection, Java's LinkedHashSet
provides a wealth of functionality to suit a variety of needs.
9. Summary
LinkedHashSet
It is an ordered and unique element storage data structure in the Java collection framework. It inherits from HashSet
, so it has the fast lookup properties of a hash table and uses a linked list to maintain the insertion order of elements. This makes it useful in situations where you need to keep elements ordered and unique.
When using LinkedHashSet
, you can control capacity and load factors as needed to balance performance and memory usage. Also, make sure to implement your custom object's hashCode()
and equals()
methods so that element uniqueness is properly handled.
Whether it is the need to store student lists, record website visit history, or other organized unique elements, LinkedHashSet
this is a reliable option that can help you solve these problems easily. I hope this blog can help beginners better understand and apply it LinkedHashSet
, and improve their Java programming skills.