• Register

Given an array, we need to copy its elements in a different array.

Method 1(Incorrect)

int a[] = {1, 8, 3};

// Create an array b[] of same size as a[]

int b[] = new int[a.length];

// Doesn't copy elements of a[] to b[], only makes

// b refer to same location

b = a;    

However, the above method is wrong.

 

EXAMPLE:-

public class Test

{

    public static void main(String[] args)

    {

        int a[] = {1, 8, 3};

  

        // Create an array b[] of same size as a[]

        int b[] = new int[a.length];

  

        // Doesn't copy elements of a[] to b[], only makes

        // b refer to same location

        b = a;    

  

        // Change to b[] will also reflect in a[] as 'a' and 

        // 'b' refer to same location.

        b[0]++;

  

        System.out.println("Contents of a[] ");

        for (int i=0; i<a.length; i++)

            System.out.print(a[i] + " ");

  

        System.out.println("\n\nContents of b[] ");

        for (int i=0; i<b.length; i++)

            System.out.print(b[i] + " ");

    }

}
Contents of a[] 
2 8 3 

Contents of b[] 
2 8 3 

OR

 Method 2(easy and correct)

We might iterate each element of the given original array and copy one element at a time. Using this method guarantees that any modifications to b, will not alter the original array a.

public class Test

{

    public static void main(String[] args)

    {

        int a[] = {1, 8, 3};

  

        // Create an array b[] of same size as a[]

        int b[] = new int[a.length];

  

        // Copy elements of a[] to b[]

        for (int i=0; i<a.length; i++)

            b[i] = a[i];

  

        // Change b[] to verify that b[] is different

        // from a[]

        b[0]++;

  

        System.out.println("Contents of a[] ");

        for (int i=0; i<a.length; i++)

            System.out.print(a[i] + " ");

  

        System.out.println("\n\nContents of b[] ");

        for (int i=0; i<b.length; i++)

            System.out.print(b[i] + " ");

    }

}
Contents of a[]

1 8 3



Contents of b[]

2 8 3

 

 

3,280 points
7 4 2