+1 vote

I have an array x which is constantly being updated. Lets say a = [1,4,9,16,25]. I want to make an exact duplicate copy of x and call it y

May 9, 2018 in Java 753 views

## 3 answers to this question.

Java Array Copy Methods

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

Arrays.copyOfRange()If only few elements of an array are to be copied, where starting index is not 0, you may use this method to copy partial array.

System.arraycopy()System class arraycopy() is the best way to do partial copy of an array. It provides you an easy way to specify the total number of elements to copy and the source and destination array index positions. For example

` System.arraycopy(source, 3, destination, 2, 8) `

will copy 8 elements from source to destination, beginning from 3rd index of source to 2nd index of destination

Arrays.copyOf(): If you want to copy first few elements of an array or full copy of array, you can use this method. It is used due to its simplcity

• 3,350 points

You can use System.arraycopy().

```int[] src  = new int[]{1,2,3,4,5};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );```
• 3,190 points
```int[] a = {1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();

//What if array a comes as local parameter? You need to use null check:

public void someMethod(int[] a) {
if (a!=null) {
int[] b = Arrays.copyOf(a, a.length);
int[] c = a.clone();
}
}```
• 6,900 points

## What is the use of toString method in Java and how can I use it ?

Whenever you require to explore the constructor ...READ MORE

## How to create a 2-D array in java?

int[][] multi = new int[5][]; multi[0] = new ...READ MORE

## How can I create File and write data in it using Java?

import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; public class WriteFiles{ ...READ MORE

+1 vote

## Are arrays equivalent to objects in Java ?

Yes; the Java Language Specification writes: In the Java ...READ MORE

+1 vote

## Remove objects from an array in Java?

We can use external libraries: org.apache.commons.lang.ArrayUtils.remove(java.lang.Object[] array, int ...READ MORE

+1 vote

## What is the syntax to declare and initialize an array in java?

You can use this method: String[] strs = ...READ MORE

## What is the syntax to initialize an array?

Rather than learning un-Official websites learn from ...READ MORE