Java Collections nCopies() Method

The nCopies() method in Java is a utility method provided by the java.util.Collections class. It is used to create an immutable list consisting of a specified number of copies of a given object. This method is useful when you need to initialize a list with repeated elements without having to manually fill it.

Table of Contents

  1. Introduction
  2. nCopies() Method Syntax
  3. Examples
    • Basic Usage of nCopies()
    • Using nCopies() with Custom Classes
  4. Real-World Use Case
  5. Conclusion

Introduction

The Collections.nCopies() method returns an immutable list containing a specified number of copies of a given object. The list is immutable, meaning that it cannot be modified after creation. This method is particularly useful for creating fixed-size lists with repeated elements, which can be used as placeholders or default values in various scenarios.

nCopies() Method Syntax

The syntax for the nCopies() method is as follows:

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

Parameters:

  • n: The number of copies of the specified object to be included in the list.
  • o: The object to be repeated in the list.

Returns:

  • An immutable list containing n copies of the specified object.

Throws:

  • IllegalArgumentException if the specified number of elements (n) is negative.

Examples

Basic Usage of nCopies()

The following example demonstrates how to use the nCopies() method to create a list with repeated elements.

Example

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

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

        // Display the list
        System.out.println("Immutable List: " + list);

        // Attempt to modify the list (will throw UnsupportedOperationException)
        try {
            list.set(0, "Hi");
        } catch (UnsupportedOperationException e) {
            System.out.println("Error: Cannot modify an immutable list");
        }
    }
}

Output:

Immutable List: [Hello, Hello, Hello, Hello, Hello]
Error: Cannot modify an immutable list

Using nCopies() with Custom Classes

You can also use the nCopies() method to create a list with repeated instances of custom class objects.

Example

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

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return name;
    }
}

public class CustomNCopiesExample {
    public static void main(String[] args) {
        // Create a student object
        Student student = new Student("Amit");

        // Create an immutable list with 3 copies of the student object
        List<Student> studentList = Collections.nCopies(3, student);

        // Display the list of students
        System.out.println("Student List: " + studentList);

        // Demonstrate that all elements in the list refer to the same object
        student.name = "Changed Name";
        System.out.println("Updated Student List: " + studentList);
    }
}

Output:

Student List: [Amit, Amit, Amit]
Updated Student List: [Changed Name, Changed Name, Changed Name]

Explanation:

  1. Immutable List: The nCopies() method creates an immutable list containing repeated instances of the specified object.

  2. Reference: In the custom class example, the list contains multiple references to the same Student object. Any changes made to the object’s fields will be reflected across all elements in the list.

Real-World Use Case

Initializing Default Values in Data Structures

In real-world applications, the nCopies() method can be used to initialize data structures with default values. This is particularly useful when you need to create a fixed-size list with placeholders or initial values for further processing.

Example

Imagine a scenario where you need to initialize a game board with default cells.

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

class Cell {
    String state;

    Cell(String state) {
        this.state = state;
    }

    @Override
    public String toString() {
        return state;
    }
}

public class GameBoardExample {
    public static void main(String[] args) {
        // Create a default cell with an initial state
        Cell defaultCell = new Cell("Empty");

        // Create an immutable list representing a game board with 9 empty cells
        List<Cell> gameBoard = Collections.nCopies(9, defaultCell);

        // Display the initial game board state
        System.out.println("Initial Game Board: " + gameBoard);

        // Demonstrate that all cells in the board refer to the same object
        defaultCell.state = "Filled";
        System.out.println("Updated Game Board: " + gameBoard);
    }
}

Output:

Initial Game Board: [Empty, Empty, Empty, Empty, Empty, Empty, Empty, Empty, Empty]
Updated Game Board: [Filled, Filled, Filled, Filled, Filled, Filled, Filled, Filled, Filled]

Explanation:

  1. Game Board Initialization: The nCopies() method is used to initialize a game board with a fixed number of cells, each set to a default state.

  2. Shared References: All elements in the list refer to the same Cell object, allowing changes to be reflected across the entire board.

Conclusion

The Collections.nCopies() method is a powerful utility for creating immutable lists with repeated elements in Java. By providing a simple way to initialize lists with fixed-size, repeated values, it enhances the flexibility and readability of your code. This method is particularly valuable in scenarios where you need to create placeholders, initialize default values, or handle repeated data in a concise and efficient manner, improving the robustness and maintainability of your Java applications.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top