Menu
Topics Index
...
`

Collections nCopies Demo - Java Example Program


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.

© meritcampus 2019

All Rights Reserved.

Open In App