Java copy array to new array

Array Copy in Java

Array in java can be copied to another array using the following ways.

  • Using variable assignment. This method has side effects as changes to the element of an array reflects on both the places. To prevent this side effect following are the better ways to copy the array elements.
  • Create a new array of the same length and copy each element.
  • Use the clone method of the array. Clone methods create a new array of the same size.
  • Use System.arraycopy() method. arraycopy can be used to copy a subset of an array.

Example

Create a java class named Tester.

public class Tester < public static void main(String args[]) < //Scenario 1: Copy array using assignment int[] a = ; int[] b = a; //test side effect b[0]++; System.out.println("Scenario 1: "); System.out.print("Array a: "); printArray(a); System.out.print("Array b: "); printArray(b); //Scenario 2: Copy array by iterating int[] c = ; int[] d = new int[c.length]; for (int i = 0; i < d.length; i++) < d[i] = c[i]; >//test side effect d[0]++; System.out.println("Scenario 2: "); System.out.print("Array c: "); printArray(c); System.out.print("Array d: "); printArray(d); //Scenario 3: Copy array using clone int[] e = ; int[] f = e.clone(); //test side effect f[0]++; System.out.println("Scenario 3: "); System.out.print("Array e: "); printArray(e); System.out.print("Array f: "); printArray(f); //Scenario 4: Copy array using arraycopy int[] g = ; int[] h = new int[g.length]; System.arraycopy(g, 0, h, 0, h.length); //test side effect h[0]++; System.out.println("Scenario 4: "); System.out.print("Array g: "); printArray(g); System.out.print("Array h: "); printArray(h); > public static void printArray(int[] a) < System.out.print("[ "); for (int i = 0; i < a.length; i++) < System.out.print(a[i] + " "); >System.out.println("]"); > >

Output

Compile and Run the file to verify the result.

Scenario 1: Array a: [ 2 2 3 ] Array b: [ 2 2 3 ] Scenario 2: Array c: [ 1 2 3 ] Array d: [ 2 2 3 ] Scenario 3: Array e: [ 1 2 3 ] Array f: [ 2 2 3 ] Scenario 4: Array g: [ 1 2 3 ] Array h: [ 2 2 3 ]

Samual Sam

Learning faster. Every day.

Источник

How to Copy One Array to Another in Java

Here you will learn how to copy one array to another in Java.

There are mainly four different ways to copy all elements of one array into another array in Java.

1. Manually
2. Arrays.copyOf()
3. System.arraycopy()
4. Object.clone()

Lets discuss each of them in brief.

How to Copy One Array to Another in Java

How to Copy One Array to Another in Java

1. Manually

In this method we manually copy elements one by one. It is not an efficient way. Below example shows how to do this.

Читайте также:  Target encoding python sklearn

2. Arrays.copyOf()

We can directly copy one array to another by using Arrays.copyOf() method. It has following syntax.

3. System.arraycopy()

It is another method that directly copies one array to another. It has following syntax.

4. Object.clone()

We can also use clone() method of Object class to make a copy of an array.

Comment below if you have any doubt related to above tutorial or you know about any other way to copy one array to another in Java.

Java Program to Find Smallest and Largest Element in an Array

Java Program to Find Union of two Arrays

Java Program to Find Intersection of two Arrays

Java Program for Addition of two Matrices

4 thoughts on “How to Copy One Array to Another in Java”

Nice post. Can you please benchmark them and post the results. I think most people will click this article to see these results.

For the copyOf function of the Array class, I see it returns an array of integers. If that’s the case why do you still instantiate the destination array (which in our case is array b)?

Thank you very much sir … it is so knowledgeable. i hope you will send me programs like this again

// Improvisation for example Arrays.copyOf(T[],int)

public class CopyArrayExample public static void main(String args[])int a[]=;
/*int b[]=new int[a.length]; no need to create another array object since
Arrays.copyOf () method itself returning array object */

//copying one array to another
int[] b=Arrays.copyOf(a,a.length);// just create a reference variable of type int [] and store the object returned by the static factory method of Arrays class i.e copyOf(T[],int) method

Источник

Array Copy in Java

Java Course - Mastering the Fundamentals

The assignment procedure would result in both variables pointing to the same array, arrays in Java cannot be copied using the = operator. Making copies of primitive types is straightforward, but you must take into account whether the copy is deep or shallow when making copies of objects or references. Java has several methods for array copying.

Introduction

Java Copy array operation will be covered in this section. Java array copy can be done using many methods provided by Java. Arrays in Java, as we know, can include items of primitive types, objects, or references. Making copies of primitive types is a simple process, but when it comes to objects or references, you must consider whether the copy is deep or shallow

Example

In this example, we are going to check how to copy an array in java using for loop.

Code Explanation

In the above example, we have created an array with elements 1,2,3 . Then created another element and assign elements to another array. This will create a copy of array. To check if a copy is created we checked it using the equals() method this method returns false means both arrays have different references.

Читайте также:  Анонимные классы java примеры

Problem with Simple Assignment Operation

We are essentially assigning a reference to the array when we write array2 = array1 . Because both array1 and array2 refer to the same location, any changes we make to one array will also affect the other arrays. We can also verify it with the code as shown below as follows:

Code Explanation

In theabovee code, we have created an array with elements 1,2,3 . Created another array and assign the previous array to the new array. As the assignment operator will assign a reference to the previous array so equals() method will return true.

Java Copy Array Various Methods

There are many methods of copying an array we are going to discuss each one of them in detail.

Manual Copying Using For Loop

Copying one element at a time while iterating through every element of the original array provided. Using this method ensures that any changes to b won’t affect the initial array a, as seen in the example below follows this example we, are going to check how to copy an array in java using for loop

Code Explanation

In above example, we have created an array with elements 1,2,3 . Then created another element and assign elements to another array. This will create a copy of array. To check if ia f copy is created we checked it usinthe g equals() method this method returns false m ns both arrays have a differenreferencesce.

Using clone() Method

The act of making an exact duplicate of an object is referred to as object cloning. It makes a new instance of the current object’s class and fills all of its fields exactly with the data found in the corresponding fields of the current object.

In this example we are going to check how to cop an array in java usinthe g clone method.

Code Explanation

In this example, we have created an array with element 1,2,3,4,5,6 . We have used the clone() method to create a copy of array array1.

Using arraycopy() Method

We can also use the System.arraycopy() Method. The system is present in `java.lang package.

This method starts the copy action from the source position to the target position till the specified length.

The target array’s length is equal to the number of elements copied there. It offers a simple method for copying a section of an array to another.

A NullPointerException is thrown if any of the array arguments are null. An IndexOutOfBoundException is thrown if any of the integer inputs are negative or outside of the acceptable range. Syntax of arraycopy() method is as follows

  • src array.
  • srcPos index from which copying starts.
  • dest stands for the destination array.
  • destPos is the index from which the copied elements are added to the destination arra.
  • length is the size of the copied subarray.
Читайте также:  Ссылка в новом окне

In this example, we are going to check how to copy an array in java using arraycopy() method.

Code Explanation

In the above code f,first, we have created an an array withelementst 1,2,3,4,5,6,7 . We have used arraycopy() method with the following parameters src:a , dest:b , srcpos:0 , destpos :0 , and length as 3 .

Using copyOf() Method of Arrays class

The function java.util.Arrays.copyOf(int[] original, int newLength) duplicates the provided array, trimming or padding with zeros (if needed) to make the copy the desired length. The two arrays will have the same values for all indices that are valid in both the original array and the duplicate. The copy will contain 0 for any indices that are accurate in the copy but not the original. Only if the given length is larger than the length of the original array will such indices be present.

original − array to be copied. newLength − length of the copy to be returned.

This method gives back a copy of the original array that has been padded with zeros or trimmed to the desired length.

In this example, we are going to discuss how to copy an array in java using the copyof() method

Code Output

Code Explanation

In the above example we have created an array with elements 1,2,3,4,5,6 and created a copyanof an array using the Arrays.copyOf() method with original arrays parameters as a and length of the array as newlength parameter.

Using copyOfRange() Method of Arrays Class

This function creates a new array by copying the desired range of the supplied array.

In this section, we are going to check how to copy an array in java using copyofRange() .

  • original: array from which to copy a range in the original
  • from: the range’s starting index to be copied
  • to: exclusive final index of the range to be copied

Code Explanation

In the above example, we have created an array with elements 1 8 3 5 9 10 and created a copy of an array using the Arrays.copyOfRange() method fthe from 2 indexthe to 6 index.

Copying 2d Arrays Using Loop

We may use the for loop to copy the 2-dimensional array like how we clone a single-dimensional array.

In this example, we are going to check how to copy an array in java of type 2D.

Code Explanation

In the above example we have created a copy of a 2D array using for loop similar top 1D array.

Conclusion

  • Because the assignment procedure would result in both variables pointing to the same array, arrays in Java cannot be copied using the = operator.
  • There arevariouss methods to copy an Object.
  • Manual Copying using for loop: copying one element at a time while iterating through every element of the original array provided
  • using clone() method
  • using arraycopy() method
  • using copyOf() method
  • using copyOfRange() method

Источник

Оцените статью