Collections.nCopies(int, List) in Java

Collections.nCopies(int, List): This method is available in java.util.Collections class of Java.

Syntax:

<List<E>> List<List<E >> java.util.Collections.nCopies(int n, List<E> o)

This method takes two arguments. This method returns an immutable list consisting of n copies of the specified object.

Parameters: Two parameters are required for this method.

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:

1. IllegalArgumentException - if n < 0.

Approach 1: When no exception

Java

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

public class CollectionsnCopies {
    public static void main(String[] args) {

        List<Integer> arrlist = new ArrayList<Integer>();

        arrlist.add(12);
        arrlist.add(5);
        arrlist.add(6);
        arrlist.add(15);

        int n = 5;
        System.out.println(Collections.nCopies(n, arrlist));

    }
}

Output:

[[12, 5, 6, 15], [12, 5, 6, 15], [12, 5, 6, 15], [12, 5, 6, 15], [12, 5, 6, 15]]


Approach 2: IllegalArgumentException 

Java

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

public class CollectionsnCopies {
    public static void main(String[] args) {

        List<Integer> arrlist = new ArrayList<Integer>();

        arrlist.add(12);
        arrlist.add(5);
        arrlist.add(6);
        arrlist.add(15);

        int n = -1;
        System.out.println(Collections.nCopies(n, arrlist));

    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: List length = -1 at java.base/java.util.Collections.nCopies(Collections.java:5107)


No comments:

Post a Comment