Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java HashSet addAll() Method

Java HashSet addAll() Method

Java HashSet Java HashSet


addAll() is a method in Java's HashSet is a commonly used method provided by the class, used to add all elements of one collection to the current HashSet . This method is inherited from AbstractCollection class and is implemented in HashSet .

Method Syntax

public

boolean

addAll

(

Collection

c ) ### Method Parameters The `addAll()` method accepts one parameter: | Parameter | Type | Description | | --- | --- | --- | | c | `Collection | the collection of elements to add to the current `HashSet` | ### Return Value The `addAll()` method returns a boolean value: - If the `HashSet` was modified by calling this method (i.e., at least one new element was added), it returns `true` - If the `HashSet` was not modified (i.e., all elements of collection `c` already exist in the current `HashSet`), it returns `false` ### Method Characteristics 1.

Deduplication Feature:HashSet will automatically remove duplicate elements, so if the added collection contains elements that already exist in the current HashSet , these duplicate elements will not be added again.

2.

Unorderedness:HashSet Does not guarantee the order of elements; the order after adding may differ from the original collection.

3.

Allows null Values:HashSet Allows 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 add.

--- ## 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 ( "Set changed: " + isChanged ) ; System . out . println ( "Merged set: " + set1 ) ; } } **Output**: ``` Set changed: true Merged set: [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**: ``` Merged set: [1, 2, 3, 4] ``` --- ## Notes 1.

Concurrent Modification: If iterating HashSet and calling addAll() method, a may be thrown ConcurrentModificationException.

2.

Empty Collection: If the passed collection is null, a will be thrown NullPointerException.

3.

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

4.

Element Equality:HashSet Use equals() and hashCode() method determines 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 bulk | --- ## 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 of sets.

4.

Initializing a Set: Use existing data to quickly initialize a new HashSet.

--- ## Performance Optimization Suggestions 1. **Estimate Capacity**: If you know the number of elements to add, you can specify the initial capacity when creating `HashSet` to reduce resizing. ## Example HashSet < String > set = new HashSet <> ( expectedSize ) ; 1.

Batch Operations: Compared to calling multiple times add(), using addAll() to add multiple elements at once is usually more efficient.

2.

Avoid Duplicate Additions: If possible, first check whether the collection to add is empty or has a large overlap with the current collection.

--- ## Frequently Asked Questions ### Q1: Does the addAll() method modify the original collection? A1: No, the `addAll()` method only modifies the `HashSet` that calls it, and 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 current `HashSet`, `addAll()` returns false, indicating that no new elements were added. ### Q3: Can you add collections of different types? A3: Yes, as long as the element types in the collection are compatible with those of the `HashSet` (same or a subclass). ### Q4: Is the addAll() method thread-safe? A4: `HashSet` itself is not thread-safe; if used in a multi-threaded environment, external synchronization is required or consider using `ConcurrentHashMap` or `Collections.synchronizedSet()`. [![Java HashSet](https://www.runoob.com/images/up.gif) Java HashSet ](/java/java-hashset.html)