banner



How to Set One Array Equal to Another Java

Given an array, we need to copy its elements in a different array, to a naive user below way comes into mind which is however incorrect as depicted below as follows:

// Java Program to Illustrate Wrong Way Of Copying an Array  // Input array int a[] = { 1, 8, 3 };  // Creating 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;

Output:

Attention reader! Don't stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course .

Output Explanation: When we do "b = a", we are actually assigning a reference to the array. Hence, if we make any change to one array, it would be reflected in other arrays as well because both a and b refer to the same location. We can also verify it with code as shown below as follows:


Example:

Java

public class Test {

public static void main(String[] args)

{

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

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

b = 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] + " " );

}

}

Output

Contents of a[]  2 8 3   Contents of b[]  2 8 3          

Methods:

We have seen internal working while copying elements and edge cases to be taken into consideration after getting through errors as generated above, so now we can propose out correct ways to copy array as listed below as follows:

  1. Iterating each element of the given original array and copy one element at a time
  2. Using clone() method
  3. Using arraycopy() method
  4. Using copyOf() method of Arrays class
  5. Using copyOfRange() method of Arrays class

Method 1: Iterating each element of the given original array and copy one element at a time. With the usage of this method, it guarantees that any modifications to b, will not alter the original array a, as shown in below example as follows:

Example:

Java

public class GFG {

public static void main(String[] args)

{

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

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

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

b[i] = a[i];

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] + " " );

}

}

Output

Contents of a[]  1 8 3   Contents of b[]  2 8 3          

Method 2: Using Clone() method


In the previous method we had to iterate over the entire array to make a copy, can we do better? Yes, we can use the clone method in Java.

Example:

Java

public class GFG {

public static void main(String[] args)

{

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

int b[] = a.clone();

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] + " " );

}

}

Output

Contents of a[]  1 8 3   Contents of b[]  2 8 3          

Method 3: Using arraycopy() method

We can also use System.arraycopy() Method. The system is present in java.lang package. Its signature is as :

public static void arraycopy(Object src, int srcPos, Object dest,                               int destPos, int length)

Parameters:

  • src denotes the source array.
  • srcPos is the index from which copying starts.
  • dest denotes the destination array
  • destPos is the index from which the copied elements are placed in the destination array.
  • length is the length of the subarray to be copied.

Example:

Java

public class GFG {

public static void main(String[] args)

{

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

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

System.arraycopy(a, 0 , b, 0 , 3 );

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] + " " );

}

}

Output

Contents of a[]  1 8 3   Contents of b[]  2 8 3          

Method 4: Using copyOf() method of Arrays class

If we want to copy the first few elements of an array or a full copy of the array, you can use this method.


Syntax:

public static int[] copyOf​(int[] original, int newLength)                  

Parameters:

  • Original array
  • Length of the array to get copied.

Example:

Java

import java.util.Arrays;

class GFG {

public static void main(String[] args)

{

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

int b[] = Arrays.copyOf(a, 3 );

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] + " " );

}

}

Output

Contents of a[]  1 8 3   Contents of b[]  2 8 3          

Method 5: Using copyOfRange() method of Arrays class

This method copies the specified range of the specified array into a new array.

public static int[] copyOfRange​(int[] original, int from, int to)

Parameters:

  • Original array from which a range is to be copied
  • Initial index of the range to be copied
  • Final index of the range to be copied, exclusive

Example:

Java

import java.util.Arrays;

class GFG {

public static void main(String[] args)

{

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

int b[] = Arrays.copyOfRange(a, 2 , 6 );

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] + " " );

}

}

Output

Contents of a[]  1 8 3 5 9 10   Contents of b[]  3 5 9 10          

Lastly, let us do discuss the overview of the above methods:

  • Simply assigning references is wrong
  • The array can be copied by iterating over an array, and one by one assigning elements.
  • We can avoid iteration over elements using clone() or System.arraycopy()
  • clone() creates a new array of the same size, but System.arraycopy() can be used to copy from a source range to a destination range.
  • System.arraycopy() is faster than clone() as it uses Java Native Interface
  • If you want to copy the first few elements of an array or a full copy of an array, you can use Arrays.copyOf() method.
  • Arrays.copyOfRange() is used to copy a specified range of an array. If the starting index is not 0, you can use this method to copy a partial array.

This article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


How to Set One Array Equal to Another Java

Source: https://www.geeksforgeeks.org/array-copy-in-java/

0 Response to "How to Set One Array Equal to Another Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel