Home  >  Core Java

Example of Collections.nCopies in Java

By Arvind Rai, May 26, 2013
In Java, Collections.nCopies role is to return an immutable which contains n copies of given object. If we want to create a list with n copies of given object then it can help us. Find the example how to use.
CollectionsnCopies.java
package com.concretepage.util;
import java.util.Collections;
import java.util.List;
public class CollectionsnCopies {
    public static void main(String[] args) {
    	Person p1 = new Person("AAAA");
        List<Person> list = Collections.nCopies(20, p1);
        System.out.println(list.size());
        //The line will throw error as the immutable list can not be changed.
        Person p2 = new Person("BBBB");
        //list.add(p2);
    }
}
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;
	}
}
Output
20
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us