What is array copy in java

Java Guides

In this article, we will learn different ways to copy an array in Java. Java provides inbuilt methods to copy the array. Whether you want a full copy or partial copy of the array, you can do it easily using java inbuilt classes.

  1. Copying Arrays using Built-in System.arraycopy() Method
  2. Copying Arrays Using Arrays.copyOf() Method
  3. Copying Arrays using Object.clone() method
  4. Copying Arrays using Arrays.copyOfRange()

1. Copying Arrays using Built-in System.arraycopy() Method

The following program, ArrayCopyDemo, declares an array of char elements, spelling the word «decaffeinated.» It uses the System.arraycopy method to copy a subsequence of array components into a second array:

arraycopy() method

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

Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. A subsequence of array components is copied from the source array referenced by src to the destination array referenced by dest.

  • src — the source array.
  • srcPos — starting position in the source array.
  • dest — the destination array.
  • destPos — starting position in the destination data.
  • length — the number of array elements to be copied.
  • IndexOutOfBoundsException — if copying would cause access of data outside array bounds.
  • ArrayStoreException — if an element in the src array could not be stored into the dest array because of a type mismatch.
  • NullPointerException — if either src or dest is null.
/** * This class shows different methods for copy array in java * @author javaguides.net * */ class ArrayCopyDemo < public static void main(String[] args) < char[] copyFrom = < 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' >; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); > >
/** * This class shows different methods for copy array in java * @author javaguides.net * */ public class JavaArrayCopyExample < public static void main(String[] args) < int[] source = < 1, 2, 3, 4, 5, 6, 7, 8, 9 >; System.out.println("Source array = " + Arrays.toString(source)); int[] temp = new int[5]; System.arraycopy(source, 0, temp, 0, 5); System.out.println( "Copy First five elements of array. Result array = " + Arrays.toString(temp)); > >
Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9] Copy First five elements of array. Result array = [1, 2, 3, 4, 5] 

2. Copying Arrays Using Arrays.copyOf() Method

If you want to copy first few elements of an array or full copy of array, you can use this method. Obviously it’s not versatile like System.arraycopy() but it’s also not confusing and easy to use. This method internally use System arraycopy() method.

import java.util.Arrays; /** * This class shows different methods for copy array in java * @author javaguides.net * */ public class JavaArrayCopyExample < public static void main(String[] args) < int[] source = < 1, 2, 3, 4, 5, 6, 7, 8, 9 >; System.out.println("Source array = " + Arrays.toString(source)); int[] dest = Arrays.copyOf(source, source.length); System.out.println( "Copy First five elements of array. Result array = " + Arrays.toString(dest)); > >
Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9] Copy First five elements of array. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9] 

3. Copying Arrays using Object.clone() method

Object class provides clone() method and since an array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want a partial copy of the array.

/** * This class shows different methods for copy array in java * @author javaguides.net * */ public class JavaArrayCopyExample < public static void main(String[] args) < int[] source = < 1, 2, 3, 4, 5, 6, 7, 8, 9 >; System.out.println("Source array = " + Arrays.toString(source)); int[] dest = source.clone(); System.out.println( "Copy First five elements of array. Result array = " + Arrays.toString(dest)); > >
Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9] Copy First five elements of array. Result array = [1, 2, 3, 4, 5, 6, 7, 8, 9] 

4. Copying Arrays using Arrays.copyOfRange()

If you want a few elements of an array to be copied, where starting index is not 0, you can use this method to copy the partial array. Again this method is also using System arraycopy method itself.

/** * This class shows different methods for copy array in java * @author javaguides.net * */ public class JavaArrayCopyExample < public static void main(String[] args) < int[] source = < 1, 2, 3, 4, 5, 6, 7, 8, 9 >; System.out.println("Source array = " + Arrays.toString(source)); int[] dest = Arrays.copyOfRange(source, source.length - 3, source.length); System.out.println( "Copy First five elements of array. Result array = " + Arrays.toString(dest)); > >
Source array = [1, 2, 3, 4, 5, 6, 7, 8, 9] Copy First five elements of array. Result array = [7, 8, 9]

Источник

Читайте также:  Javascript событие страница загружена

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.

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:

Читайте также:  Java file get relative path

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.
Читайте также:  Си шарп класс array

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

Источник

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