Set an Array Equal to Another Array in Java

[ad_1]

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.

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.

Output:

a: 1 2 3 4 5
b: 2 2 3 4 5

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.


The method requires the following arguments,

  • src: The source array from which the elements are to be copied.
  • srcPos: The starting position in the src 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 or dest are null, method throws this exception.

  • ArrayStoreException: The method throws this exception in various cases as given below.

    • If the src or dest is not an array.
    • If there is a type mismatch between the src and dest array. For example if one of the arrays is of type int and other is of type String, method throws this exception.
  • IndexOutOfBoundsException: This exception signifies that an array is being accessed beyond its assigned memory limit.

    So in case you provide negative srcPos and destPos or if length 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.

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:

a: 1 2 3 4 5
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.

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 null
  • NegativeArraySizeException: If the newLength argument is negative.

Let us see the code.

Output:

a: 1 2 3 4 5
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.

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 if original is null.
  • IllegalArgumentException: The method throws this exception if from is greater than to.
  • ArrayIndexOutOfBoundsException: The method throws this argument if the from is negative or is greater than the length of the original array.

Let us see the code example.

Note that the code copies only second and third elements of first array to the second array.

Output:

a: 1 2 3 4 5
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.

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:

a: 1 2 3 4 5
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!

[ad_2]

Leave a Comment