Collections.copy(List, List) in Java

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

Syntax:

<E> void java.util.Collections.copy(List<? super E> dest, List<? extends E> src)

This method takes two arguments. This method copies all of the elements from one list into another.

Note: After the operation, the index of each copied element in the destination list will be identical to its index in the source list.

Parameters: Two parameters are required for this method.

dest: The destination list.

src: The source list.

Throws:

1. IndexOutOfBoundsException - if the destination list is too small to contain the entire source List.

2. UnsupportedOperationException - if the destination list's list-iterator does not support the set operation.

Approach 1: When no exception

Java

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

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

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

        arrlist.add(12);

        arrlist.add(13);
        arrlist.add(4);

        List<Integer> arrlist2 = new ArrayList<Integer>();
        arrlist2.add(1000);
        arrlist2.add(10000);
        arrlist2.add(100);
        Collections.copy(arrlist2, arrlist);

        System.out.println(arrlist2);

    }
}

Output:

[12, 13, 4]


Approach 2: IndexOutOfBoundsException 

Java

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

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

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

        arrlist.add(12);

        arrlist.add(13);
        arrlist.add(4);

        List<Integer> arrlist2 = new ArrayList<Integer>();
        arrlist2.add(1000);
        arrlist2.add(10000);
        Collections.copy(arrlist2, arrlist);

        System.out.println(arrlist2);

    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest at java.base/java.util.Collections.copy(Collections.java:561)


No comments:

Post a Comment