Menu
Topics Index
...
`


Collections Framework > Collection Algorithms >
Siva Nookala - 01 Apr 2016
When we need to create a Collection containing multiple copies of an object, then we can use nCopies method. This creates an immutable List containing the specified number of copies of the given object.

public static <T> List<T> nCopies(int n, T o)
Here n is the number of Objects and o is the object which needs to be copied.
Collections nCopies Demo
import java.util.*;

class CollectionsNCopiesDemo
{
    public static void main(String arg[])
    {
        List<String> robosEveryWhere = Collections.nCopies(3, "Robot");
        System.out.println("All Robos : " + robosEveryWhere);
        
        Student rama = new Student("Rama", 12, 'B');
        List<Student> numerousRamas = Collections.nCopies(10, rama);
        System.out.println("Numerous Ramas : " + numerousRamas);
        
        // CHANGE ONE STUDENT EVERY STUDENT IS CHANGED
        // SINCE ALL REFERENCES POINT TO THE SAME OBJECT.
        numerousRamas.get(4).section = 'D'; // LINE A
        System.out.println("After Changing : " + numerousRamas);
    
    }
}

class Student
{
    String name;
    int marks;
    char section;
    
    Student(String name, int marks, char section)
    {
        this.name = name;
        this.marks = marks;
        this.section = section;
    }

    public String toString()
    {
        return name + "-" + marks + "-" + section;
    }
}
OUTPUT

All Robos : [Robot, Robot, Robot]
Numerous Ramas : [Rama-12-B, Rama-12-B, Rama-12-B, Rama-12-B, Rama-12-B, Rama-12-B, Rama-12-B, Rama-12-B, Rama-12-B, Rama-12-B]
After Changing : [Rama-12-D, Rama-12-D, Rama-12-D, Rama-12-D, Rama-12-D, Rama-12-D, Rama-12-D, Rama-12-D, Rama-12-D, Rama-12-D]

DESCRIPTION

Using the nCopies method provided in Collections, we creating a List with the required number of copies. Initially we created a String List containing three "Robot"s. Later we tried to create multiple copies for Student rama. One thing we need to note is these nCopies are only the copies of the references and not the copies of the Student object. Which means all the references point to same object and so when we changed the section to D at LINE A, the section changed for all the Students.

THINGS TO TRY
  • Try creating 20 copies of an Double object.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.