Collections.nCopies method in Java

realNameHidden - Sep 29 - - Dev Community

For Explanation watch video

The Collections.nCopies method in Java is used to create an immutable list consisting of the same object repeated a specified number of times. This method is part of the java.util.Collections class.

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

Enter fullscreen mode Exit fullscreen mode

Parameters
n: The number of times to repeat the object in the list.
o: The object to be repeated in the list.

Return Value
The method returns an immutable list containing n copies of the specified object.

Key Points

The list returned is immutable, meaning you cannot modify it (e.g., you cannot add or remove elements).

Each element in the list is a reference to the same object, not different instances of the object.

import java.util.Collections;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Create an immutable list with 5 copies of the string "Hello"
        List<String> list = Collections.nCopies(5, "Hello");

        // Print the list
        System.out.println(list);

        // Try modifying the list (this will throw an UnsupportedOperationException)
        try {
            list.add("World");
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify the list: " + e.getMessage());
        }

        // Print the individual elements of the list
        for (String s : list) {
            System.out.println(s);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

[Hello, Hello, Hello, Hello, Hello]
Cannot modify the list: null
Hello
Hello
Hello
Hello
Hello

Enter fullscreen mode Exit fullscreen mode

Explanation

  1. Creating the List:

List list = Collections.nCopies(5, "Hello"); creates a list with 5 references to the same string "Hello".

  1. Printing the List:

System.out.println(list); prints the list, showing [Hello, Hello, Hello, Hello, Hello].

  1. Modifying the List:

list.add("World"); attempts to add an element to the list, but since the list is immutable, it throws an UnsupportedOperationException.

  1. Iterating Over the List:

A for-each loop prints each element of the list, showing "Hello" five times.

Important Considerations

The method returns an immutable list, so any attempt to modify the list (e.g., adding or removing elements) will result in an UnsupportedOperationException.

All elements in the list are references to the same object. If the object is mutable and its state is changed, the change will be reflected in all references within the list.

import java.util.Collections;
import java.util.List;

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "'}";
    }
}

public class Main {
    public static void main(String[] args) {
        // Create a mutable Person object
        Person person = new Person("John");

        // Create an immutable list with 3 references to the same Person object
        List<Person> list = Collections.nCopies(3, person);

        // Print the list
        System.out.println(list);

        // Change the name of the Person object
        person.setName("Jane");

        // Print the list again to see the changes
        System.out.println(list);

        // Verify that all elements in the list reflect the change
        for (Person p : list) {
            System.out.println(p.getName());
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

output

[Person{name='John'}, Person{name='John'}, Person{name='John'}]
[Person{name='Jane'}, Person{name='Jane'}, Person{name='Jane'}]
Jane
Jane
Jane

Enter fullscreen mode Exit fullscreen mode
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .