Table of Contents
- Setting an Array Variable Equal to Another Array Variable
- Set an Array Equal to Another Array in Java Using the clone() Method
- Set an Array Equal to Another Array in Java Using the arraycopy() Method
- Set an Array Equal to Another Array in Java Using the copyOf() Method
- Set an Array Equal to Another Array in Java Using the copyOfRange() Method
- Copying Array Elements by Iterating the Array
- Conclusion
This article discusses methods to set an array equal to another array in Java.
Arrays are the most basic data structures that store the data at contiguous memory locations. The operations on the array elements are performed using the indices.
Setting an Array Variable Equal to Another Array Variable
It might seem logical to set an array variable equal to another array variable to copy the elements of the array.
However, there is a catch. When you set an array variable equal to another array variable, both of the variables have the reference.
Therefore, instead of copying the array elements, reference is copied. In this case if you change array elements using one of the array variable, changes are reflected in both of the array variables.
Hence, you can not copy the array elements by simple assignment operator (=).
Set an Array Equal to Another Array in Java Using the clone() Method
The clone()
method creates a copy of the object that calls it and returns the copied object reference.
Note that this method creates a deep copy. It means the separate memory is allocated to the new object.
This method is defined in the object class and returns an object of type Object
. The definition of the clone()
method is given below.
1 2 3 4 |
protected Object clone() throws CloneNotSupportedException |
The method throws a CloneNotSupportedException
in the case where the clone of the object could not be created.
The object of those classes that does not implement the Cloneable
interface can not be cloned. In such cases the clone()
method throws the exception. If you are overriding the clone()
method your implementation should also throw the exception.
Let us say you have an object obj1
and you call clone()
on it. You store the results in obj2
. Then in that case, obj2
and obj1
contain different reference and hence are not equal.
Let us see an example code in Java that clones an array into another array using clone()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package java2blog; public class ArrayExample { public static void main(String[] args) { int a [] = {1, 2, 3, 4, 5}; int b [] = a.clone(); System.out.print("a: "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); System.out.print("b: "); b[0]++; for(int i=0;i<b.length;i++) System.out.print(b[i]+" "); } } |
Output:
b: 2 2 3 4 5
Further reading:
Set an Array Equal to Another Array in Java Using the arraycopy() Method
The arraycopy()
method of the System class copies an array starting from a specific position to another array starting from a specific position.
Let us see the definition of the method.
1 2 3 4 5 6 7 |
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) |
The method requires the following arguments,
src
: The source array from which the elements are to be copied.srcPos
: The starting position in thesrc
from where the elements are copied.dest
: The destination array to which the elements are to be copied.destPos
: The position in destination array where the elements are to be copied.length
: number of elements to be copied.
The method throws various exceptions as well. Let us see each one of them.
-
NullPointerException: If the
src
ordest
are null, method throws this exception. -
ArrayStoreException
: The method throws this exception in various cases as given below.- If the
src
ordest
is not an array. - If there is a type mismatch between the
src
anddest
array. For example if one of the arrays is of typeint
and other is of typeString
, method throws this exception.
- If the
-
IndexOutOfBoundsException
: This exception signifies that an array is being accessed beyond its assigned memory limit.So in case you provide negative
srcPos
anddestPos
or iflength
is more than number of elements, the method raises this exception.
Let us see the code to copy an array into another array using this method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package java2blog; public class ArrayExample { public static void main(String[] args) { int a [] = {1, 2, 3, 4, 5}; int b [] = new int [a.length]; System.arraycopy(a, 0, b, 0, a.length); System.out.print("a: "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); System.out.print("b: "); b[0]++; for(int i=0;i<b.length;i++) System.out.print(b[i]+" "); } } |
Note that the arraycopy()
method is a static method of System class. So you can invoke it with class name only without creating the object.
Output:
b: 2 2 3 4 5
Set an Array Equal to Another Array in Java Using the copyOf() Method
The copyOf()
method copies the content of an array and returns a new array.
The method takes two arguments, the reference of original array and length
denoting the number of elements to be copied starting from beginning.
Let us see the definition of the copyOf()
method.
1 2 3 4 |
public static int[] copyOf(int[] original, int newLength) |
Note that this method can truncate or pad the copied array with zeros. Padding will happen when the provided length is greater than the number of elements in the array.
This method throws two exceptions as given below.
NullPointerException
: If the original array is nullNegativeArraySizeException
: If thenewLength
argument is negative.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package java2blog; import java.util.Arrays; public class ArrayExample { public static void main(String[] args) { int a [] = {1, 2, 3, 4, 5}; int b [] = Arrays.copyOf(a, a.length); System.out.print("a: "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); System.out.print("b: "); b[0]++; for(int i=0;i<b.length;i++) System.out.print(b[i]+" "); } } |
Output:
b: 2 2 3 4 5
Set an Array Equal to Another Array in Java Using the copyOfRange() Method
If you need to copy the elements of an array within a particular range, then the copyOfRange()
is a better option.
This method works similar to the copyOf()
method except that it accepts three arguments specifying the range to be copied.
Let us see definition of the copyOfRange()
method.
1 2 3 4 5 |
public static <T> T[] copyOfRange(T[] original, int from, int to) |
The method definition specifies the generic template type so that it can be used with all of the data types.
The first argument original
is the reference of the original array from where the elements are to be copied.
The second argument from
specifies the starting point from where the elements will be copied.
The last argument to
marks the end of the range. It means the elements from original array are copied till here to the new array.
This method throws the following exceptions.
NullPointerException
: The method throws this exception iforiginal
is null.IllegalArgumentException
: The method throws this exception iffrom
is greater thanto
.ArrayIndexOutOfBoundsException
: The method throws this argument if thefrom
is negative or is greater than the length of the original array.
Let us see the code example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package java2blog; import java.util.Arrays; public class ArrayExample { public static void main(String[] args) { int a [] = {1, 2, 3, 4, 5}; int b [] = Arrays.copyOfRange(a, 1, a.length-2); System.out.print("a: "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); System.out.print("b: "); for(int i=0;i<b.length;i++) System.out.print(b[i]+" "); } } |
Note that the code copies only second and third elements of first array to the second array.
Output:
b: 2
Copying Array Elements by Iterating the Array
One of the easiest method to copy the array elements is to iterate the first array using indices and assigning each element to corresponding index of second array.
You can iterate the array elements using any of the loops.
Let us see the code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package java2blog; public class ArrayExample { public static void main(String[] args) { int a [] = {1, 2, 3, 4, 5}; int b [] = new int [a.length]; for(int i=0;i<a.length;i++) { b[i]=a[i]; } System.out.print("a: "); for(int i=0;i<a.length;i++) System.out.print(a[i]+" "); System.out.println(); System.out.print("b: "); b[0]++; for(int i=0;i<b.length;i++) System.out.print(b[i]+" "); } } |
Note that the length
variable in the array stores the number of elements in the array. The code copies the first array to the second array.
However the code also changes the first element of second array. You may notice that only element of second array is changed and first array remains same.
Output:
b: 2 2 3 4 5
Conclusion
You have seen different methods of copying the array elements. While using the predefined methods, you can avoid iterations. Also, arraycopy()
method is faster than clone()
method.
Therefore, it is logical to select the method that suits best as per the needs. For example if you need to copy elements within a range the best suited method is copyOfRange()
method.
This is all about how to set an array equal to another array in Java.
Hope you enjoyed reading the article. Stay tuned for more articles. Happy Learning!