Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collections.nCopies()

Returns an unmodifiable list of n identical elements.

Available since: Java 1.2

Syntax

public static <T> List<T> nCopies(int n, T o)

Parameters

ParameterTypeDescription
nintHow many times to repeat the element.
oTThe element to repeat.

Return value

List<T>An unmodifiable list of length n.

Examples

Repeating an element and building a separator line:

void main() {
    IO.println(Collections.nCopies(3, "ab"));
    IO.println(String.join("+", Collections.nCopies(4, "1")));
}

Output:

[ab, ab, ab]
1+1+1+1

A modifiable list filled with zeros:

void main() {
    List<Integer> slots = new ArrayList<>(Collections.nCopies(5, 0));
    slots.set(2, 7);
    IO.println(slots);
}

Output:

[0, 0, 7, 0, 0]

Notes

The list does not store n copies: it remembers one object and a number, so it takes little memory even for a million elements. All elements are the same object, which is a trap for mutable objects such as lists. For a string, "-".repeat(10) is simpler.

See also

  • String.repeat() — Repeats a string the given number of times.
  • Arrays.fill() — Fills the whole array or part of it with one value.
  • ArrayList — A resizable list backed by an array — the most common `List` implementation.
  • String.join() — Joins strings with a separator.

In the tutorial

  • Collection helper methods — The Collections class and useful Java methods: max, min, frequency, reverse, shuffle, nCopies, unmodifiable copies and views, Arrays.asList.

Thanks for reading!

Donate to the site — we work hard for you.