Collections static void copy(List dest,List src) method Example Program


Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.

Program

package com.candidjava;

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

/**
 * @author : karthikeyan.T
 * @description : the following code shows how to use Collections.copy(List dest, List src) method.
 * */
public class Copy {
	public static void main(String[] args) {
		List als = new ArrayList();
		List ald = new ArrayList();
		als.add("mohan");
		als.add("karthik");
		als.add("hari");
		als.add("kamal");
		als.add("anand");
		als.add("vinodh");
		ald.add("Hai mohan");
		ald.add("Hai karthik");
		ald.add("Hai hari");
		ald.add("Hai kamal");
		ald.add("Hai anand");
		ald.add("Hai vinodh");
		System.out.println("List 1 : " + als);
		System.out.println("List 2 : " + ald);
		Collections.copy(ald, als);
		System.out.println();
		System.out.println("List 1 copied to List 2 : " + ald);
	}
}

Output

List 1 : [mohan, karthik, hari, kamal, anand, vinodh]
List 2 : [Hai mohan, Hai karthik, Hai hari, Hai kamal, Hai anand, Hai vinodh]

List 1 copied to List 2 : [mohan, karthik, hari, kamal, anand, vinodh]

Explanation

public static void copy(List dest,List src)
Copies all of the elements from one list into another. After the operation, the index of each copied element in the destination list will be identical to its index in the source list. The destination list must be at least as long as the source list. If it is longer, the remaining elements in the destination list are unaffected.
This method runs in linear time.

Parameters:
dest - The destination list.
src - The source list.
Throws:
IndexOutOfBoundsException - if the destination list is too small to contain the entire source List.
UnsupportedOperationException - if the destination list's list-iterator does not support the set operation.


Related Post

Comments


©candidjava.com