Collections public static List nCopies(int n, T o) Method Example Program


Returns an immutable list consisting of n copies of the specified object.

Program

package com.candidjava;

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

/**
 * 
 * @author karthikeyan.T
 * @description the following code shows how to use Collections.nCopies(int n, T
 *              o) method.
 */
public class CollectionsNcopies {
		public static void main(String[] args) {
			List<String> list = Collections.nCopies(5, "CandidJava");
			System.out.println(list);
		}
	}

Output

[CandidJava, CandidJava, CandidJava, CandidJava, CandidJava]

Explanation

public static <T> List<T> nCopies(int n, T o)
Returns an immutable list consisting of n copies of the specified object. The newly allocated data object is tiny (it contains a single reference to the data object). This method is useful in combination with the List.addAll method to grow lists. The returned list is serializable.
Parameters:
n - the number of elements in the returned list.
o - the element to appear repeatedly in the returned list.
Returns:
an immutable list consisting of n copies of the specified object.
Throws:
IllegalArgumentException - if n < 0
See Also:
List.addAll(Collection), List.addAll(int, Collection)


Related Post

Comments


©candidjava.com