In Java, Collections.fill(list, value) replaces every existing element of a List with the same value. The size of the list does not change, and the method returns nothing.
The key word is existing: fill overwrites positions that are already there. It never adds elements, so filling an empty list leaves it empty. To create a list of repeated values, use nCopies.
A static method of the java.util.Collections utility class, available since Java 1.2. Call it on the class name, as in Collections.fill(...), after import java.util.Collections;. You never create a Collections object.
Syntax
Pass the list and the value to write into every position.
fill runs in linear time. Every position receives the same reference, so filling with a mutable object (such as a StringBuilder) means all positions share one object.
Library declarations
Java
// java.util.Collections
public static <T> void fill(List<? super T> list, T obj)
Parameters
Parameter
Description
list
The list whose elements are replaced. It must support set.
obj
The value to store in every position. May be null if the list allows it.
Changeable copy. Six dots come from nCopies, wrapped in new ArrayList<>(...) so the list can be edited.
A window of three.subList(2, 5) covers indexes 2, 3, and 4, and only those become #.
Joined for display.String.join("", pixels) prints the row as ..###..
Immutable source. The list returned directly by nCopies cannot be changed, so filling it throws UnsupportedOperationException.
Frequently Asked Questions
It replaces every element of a List with the same value. The size does not change.
new ArrayList<>(n) creates an empty list with room for n elements. fill only overwrites existing elements, so nothing happens. Use new ArrayList<>(Collections.nCopies(n, value)) instead.
Yes. Fill a subList view: Collections.fill(list.subList(from, to), value).
Collections.fill works on a List. Arrays.fill works on arrays, including primitive arrays such as int[].
No. Every position gets the same reference. With mutable objects, changing one position changes them all.