Java HashSet addAll() Method

Java HashSet Java HashSet


addAll()is in JavaHashSeta common method provided by the class, used to add all elements from a collection to the currentHashSet. This method is inherited from theAbstractCollectionclass, and is implemented inHashSet.

Method Syntax

public boolean addAll(Collection<? extends E> c)

Method Parameters

addAll()The method accepts one parameter:

Parameter Type Description
c Collection<? extends E> to be added to the currentHashSetthe collection of elements in the

Return Value

addAll()The return value of the method is a boolean value:

  • IfHashSethas changed due to calling this method (i.e., at least one new element was added), then returnstrue
  • IfHashSethas not changed (i.e., the collectioncall elements in the [collection] already exist in the currentHashSet), then returnsfalse

Method Characteristics

  1. Deduplication Feature:HashSetAutomatically removes duplicate elements, so if any elements in the added collection already exist in the currentHashSet, these duplicate elements will not be added again.

  2. Unordered Nature:HashSetThe order of elements is not guaranteed; the order after addition may differ from the original collection.

  3. Allows null Values:HashSetAllows adding null values, but only one null value (because it is a set).

  4. Performance Considerations:addAll()The time complexity of the method is approximately O(n), where n is the number of elements to be added.


Usage Examples

Example 1: Basic Usage

Example

import java.util.HashSet;
import java.util.Arrays;

public class HashSetAddAllExample {
    public static void main(String[] args) {
        // Create the first HashSet
        HashSet<String> set1 = new HashSet<>();
        set1.add("Apple");
        set1.add("Banana");
       
        // Create the second collection
        HashSet<String> set2 = new HashSet<>();
        set2.add("Orange");
        set2.add("Grape");
        set2.add("Apple"); // Duplicate element
       
        // Use the addAll() method
        boolean isChanged = set1.addAll(set2);
       
        System.out.println("Whether the set has changed: " + isChanged);
        System.out.println("Merged set: " + set1);
    }
}

Output Result:

集合是否改变: true
合并后的集合: [Apple, Grape, Orange, Banana]

Example 2: Using with Other Collection Types

Example

import java.util.HashSet;
import java.util.ArrayList;

public class HashSetAddAllExample2 {
    public static void main(String[] args) {
        HashSet<Integer> numberSet = new HashSet<>();
        numberSet.add(1);
        numberSet.add(2);
       
        ArrayList<Integer> numberList = new ArrayList<>();
        numberList.add(3);
        numberList.add(4);
        numberList.add(2); // Duplicate element
       
        numberSet.addAll(numberList);
       
        System.out.println("Merged set: " + numberSet);
    }
}

Output Result:

合并后的集合: [1, 2, 3, 4]

Notes

  1. Concurrent Modification: If while iterating over theHashSetyou call theaddAll()method, it may throwConcurrentModificationException。

  2. Empty Collection: If the passed collection is null, it will throwNullPointerException。

  3. Performance Impact: For large collections,addAll()the operation may require more time and memory.

  4. Element Equality:HashSetUseequals()andhashCode()methods to determine whether elements are equal, ensuring that custom classes correctly implement these two methods.


Comparison with the add() Method

Feature add() addAll()
Number of elements added Single element Multiple elements
Return value Returns false if the element already exists Returns true if at least one new element is added
Use case When adding elements one by one When adding elements in batches

Practical Application Scenarios

  1. Merging multiple data sources: When you need to collect data from multiple data sources and remove duplicates.

  2. Data deduplication: Quickly convert a list into a set without duplicate elements.

  3. Set operations: Implement the union operation on sets.

  4. Initialize a set: Quickly initialize a new using existing dataHashSet。


Performance Optimization Suggestions

  1. Estimate capacity: If you know the number of elements to add, you can when creatingHashSetspecify the initial capacity to reduce resize operations.

Example

HashSet<String> set = new HashSet<>(expectedSize);
  1. Batch operations: Compared to calling multiple timesadd(), usingaddAll()to add multiple elements at once is usually more efficient.

  2. Avoid duplicate additions: If possible, first check whether the collection to be added is empty or has significant overlap with the current set.


FAQ

Q1: Does the addAll() method modify the original collection?

A1: No,addAll()the method only modifies the that calls it,HashSetand does not modify the collection passed as a parameter.

Q2: Why does addAll() sometimes return false?

A2: When all elements in the collection to be added already exist in the currentHashSet, thenaddAll()it will return false, indicating that no new elements were added.

Q3: Can collections of different types be added?

A3: Yes, as long as the element type of the collection is compatible withHashSetthe element type of (the same or a subclass).

Q4: Is the addAll() method thread-safe?

A4: HashSetitself is not thread-safe. If used in a multi-threaded environment, external synchronization is needed, or consider usingConcurrentHashMaporCollections.synchronizedSet()。

Java HashSet Java HashSet

other extensions