[Java Basics] Detailed explanation of Java LinkedHashSet: the perfect choice for ordered unique element storage

Insert image description here

The collection framework in Java provides a variety of data structures for storing and manipulating data. LinkedHashSetIt 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?

LinkedHashSetIt 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 LinkedHashSethaving the following two main properties:

  • Order : LinkedHashSetThe 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 HashSetas , LinkedHashSetensuring the uniqueness of elements and not allowing duplicate elements.

Therefore, LinkedHashSetit 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 LinkedHashSetobject, 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 LinkedHashSetobject 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 LinkedHashSetover the performance and memory footprint of .

2.3. Create from existing collection

You can also create one from an existing collection such as Listor to convert between different collection types:SetLinkedHashSet

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

LinkedHashSetCommon collection operations are provided, including adding, deleting, and querying elements. Here are some examples of basic operations:

3.1. Adding elements

Use addthe method to LinkedHashSetadd elements to :

linkedHashSet.add("D");
linkedHashSet.add("E");

3.2. Delete elements

Use removethe method to remove elements LinkedHashSetfrom :

linkedHashSet.remove("B");

3.3. Query whether an element exists

Use containsthe method to check if an element exists in LinkedHashSet:

boolean containsC = linkedHashSet.contains("C");

4. Traverse LinkedHashSet

Iterating LinkedHashSetover 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, LinkedHashSetelements will be returned in the order in which they were inserted, thus maintaining order.

5. Performance considerations for LinkedHashSet

LinkedHashSetThe performance is HashSetsimilar to , and the time complexity of finding elements is O(1), which is achieved through a hash table. But unlike HashSet, LinkedHashSetyou also need to maintain the linked list structure, so adding and removing elements may be HashSetslightly slower than . But usually, this performance loss is negligible.

It is important to note that LinkedHashSetthe 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

LinkedHashSetThere are some things to consider when using :

  • LinkedHashSetIt is thread-unsafe. If used in a multi-threaded environment, thread synchronization issues need to be considered, or thread-safe collection classes should be considered ConcurrentLinkedHashSet.
  • LinkedHashSetIt is allowed to store an nullelement, but it is generally recommended to avoid nullstoring as a valid element to avoid confusion and errors.
  • When using a custom object as LinkedHashSetan element, you need to implement hashCode()the and equals()methods correctly to ensure the uniqueness and correctness of the object in the collection.
  • LinkedHashSetThe 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 LinkedHashSetdo 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 LinkedHashSetto 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 LinkedHashSetthe 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 LinkedHashSetif is empty, it will return if there are no elements in the collection, trueotherwise 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 LinkedHashSetall 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 LinkedHashSetcopy, 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 LinkedHashSetconvert 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 LinkedHashSetfor equality, you can use equals()the method. Two LinkedHashSetare 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 ConcurrentModificationExceptionexceptions.

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 LinkedHashSetand 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 LinkedHashSetprovides a wealth of functionality to suit a variety of needs.

9. Summary

LinkedHashSetIt 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, LinkedHashSetthis 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.

Guess you like

Origin blog.csdn.net/qq_21484461/article/details/132818993