Collections.addAll: Bulk Addition with Varargs
You'll learn how to efficiently add multiple elements to any collection in one convenient call using Collections.addAll().
When you need to add several elements to a collection, you could call add() repeatedly—but there's a faster, cleaner way. The Collections.addAll() method takes a collection and a varargs parameter, letting you add multiple elements in a single statement.
The Core Idea
Collections.addAll() is a static utility method with this signature:
static <T> boolean addAll(Collection<? super T> c, T... elements)
It accepts any Collection as the first argument, followed by any number of elements to add. The varargs syntax (T...) means you can pass elements as comma-separated values without creating an array manually.
Think of it like a grocery bag: instead of placing items one at a time into your cart, you dump the entire bag's contents in at once—much faster and more convenient.
Why Use It?
- Conciseness: One line instead of multiple
add()calls - Performance: More efficient than repeated individual additions
- Readability: Intent is crystal clear at a glance
Basic Example
List<String> fruits = new ArrayList<>();
Collections.addAll(fruits, "apple", "banana", "cherry", "date");
// fruits now contains all four elements
Set<Integer> numbers = new HashSet<>();
Collections.addAll(numbers, 1, 2, 3, 4, 5);
// numbers now contains all five integers
This works with any Collection type—lists, sets, queues, deques—making it universally useful for initialization or bulk updates.
Key Takeaway: Use Collections.addAll(collection, elem1, elem2, ...) to add multiple elements to any collection efficiently with clean, readable varargs syntax—it's faster and more expressive than repeated add() calls.