Course contentsShow
← Java
Lesson 1270 of 2,87028. Collections Utility ClassFree lesson

Collections.fill: Setting All Elements to a Value

Replace every element in a list with a specified value using fill(), useful for resetting or initializing lists.

Collections.fill: Setting All Elements to a Value

What you'll learn: How to quickly replace every element in a list with the same specified value using Collections.fill().

The Core Idea

Sometimes you need to reset a list or initialize all its elements to the same value—perhaps clearing a game board to zeros, marking all checkboxes as unchecked, or setting default values. Instead of looping through the list manually, Collections.fill() does this in one line.

Think of it like using a paint roller to cover an entire wall with the same color, rather than carefully painting each spot individually.

How It Works

The fill() method takes two parameters: the list you want to modify and the value you want to set for every element. It replaces all existing elements with that value.

import java.util.*;

public class FillDemo {
    public static void main(String[] args) {
        List<String> tasks = new ArrayList<>(Arrays.asList("Email", "Call", "Meeting", "Report"));
        System.out.println("Before: " + tasks);
        
        // Replace all elements with "Pending"
        Collections.fill(tasks, "Pending");
        System.out.println("After: " + tasks);
        // Output: [Pending, Pending, Pending, Pending]
        
        // Works with numbers too
        List<Integer> scores = new ArrayList<>(Arrays.asList(85, 92, 78, 88));
        Collections.fill(scores, 0);
        System.out.println("Reset scores: " + scores);
        // Output: [0, 0, 0, 0]
    }
}

Important Notes

  • The list size doesn't change—only the values are replaced
  • The list must be modifiable (won't work on immutable lists)
  • Works with any List implementation that supports set()

Key Takeaway: Use Collections.fill() to efficiently replace every element in a list with the same value—perfect for resetting or initializing list contents without manual iteration.