Java скопировать массив char

Java Arrays — copyOf() Method

The Java Arrays copyOf(char[] original,int newLength) method copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain false. Such indices will exist if and only if the specified length is greater than that of the original array.

Declaration

Following is the declaration for java.util.Arrays.copyOf(char[] original,int newLength) method

public static char[] copyOf(char[] original,int newLength)

Parameters

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

Return Value

This method returns a copy of the original array, truncated or padded with false elements to obtain the specified length.

Exception

  • NegativeArraySizeException − If newLength is negative.
  • NullPointerException − If original is null.

Example 1

The following example shows the usage of Java Arrays copyOf() method. First, we’ve created an array of chars. We’ve printed them. A copy of array with same size is created using copyOf() method and printed.

package com.tutorialspoint; import java.util.Arrays; public class ArrayDemo < public static void main(String[] args) < char[] charArr = < 'A', 'B', 'C', 'D' >; System.out.print("Char Array: ["); for (int i = 0; i < charArr.length; i++) < System.out.print(charArr[i] + " "); >System.out.print("]\nCopied Array: \n"); // Create copy of the array of same size char[] charArrCopy = Arrays.copyOf(charArr, charArr.length); System.out.print("Char Array: ["); for (int i = 0; i < charArrCopy.length; i++) < System.out.print(charArrCopy[i] + " "); >System.out.print("]"); > >

Output

Let us compile and run the above program, this will produce the following result −

Char Array: [A B C D ] Copied Array: Char Array: [A B C D ]

Example 2

The following example shows the usage of Java Arrays copyOf() method. First, we’ve created an array of chars. We’ve printed them. A copy of array with higher size is created using copyOf() method and printed.

package com.tutorialspoint; import java.util.Arrays; public class ArrayDemo < public static void main(String[] args) < char[] charArr = < 'A', 'B', 'C', 'D' >; System.out.print("Char Array: ["); for (int i = 0; i < charArr.length; i++) < System.out.print(charArr[i] + " "); >System.out.print("]\nCopied Arrays: \n"); // Create copy of the array of greater size char[] charArrCopy = Arrays.copyOf(charArr, charArr.length + 1); System.out.print("Char Array: ["); for (int i = 0; i < charArrCopy.length; i++) < System.out.print(charArrCopy[i] + " "); >System.out.print("]"); > >

Output

Let us compile and run the above program, this will produce the following result −

Char Array: [A B C D ] Copied Array: Char Array: [A B C D ]

Example 3

The following example shows the usage of Java Arrays copyOf() method. First, we’ve created an array of chars. We’ve printed them. A copy of array with lower size is created using copyOf() method and printed with default values appended.

package com.tutorialspoint; import java.util.Arrays; public class ArrayDemo < public static void main(String[] args) < char[] charArr = < 'A', 'B', 'C', 'D' >; System.out.print("Char Array: ["); for (int i = 0; i < charArr.length; i++) < System.out.print(charArr[i] + " "); >System.out.print("]\nCopied Arrays: \n"); // Create copy of the array of lesser size char[] charArrCopy = Arrays.copyOf(charArr, charArr.length - 1); System.out.print("Char Array: ["); for (int i = 0; i < charArrCopy.length; i++) < System.out.print(charArrCopy[i] + " "); >System.out.print("]"); > >

Output

Let us compile and run the above program, this will produce the following result −

Char Array: [A B C D ] Copied Array: Char Array: [A B C ]

Источник

Читайте также:  Java main args exception

Arrays.copyOf in Java With Example

Arrays.copyOf in Java With Example | The copyOf() method of java.util.Arrays class copies the specified array, truncating or padding with zeros/nulls (if necessary). Internally, this method calls the System.arraycopy() method of Java.

  • public static byte[] copyOf(byte[] original, int newLength)
  • public static short[] copyOf(short[] original, int newLength)
  • public static int[] copyOf(int[] original, int newLength)
  • public static long[] copyOf(long[] original, int newLength)
  • public static char[] copyOf(char[] original, int newLength)
  • public static float[] copyOf(float[] original, int newLength)
  • public static double[] copyOf(double[] original, int newLength)
  • public static boolean[] copyOf(boolean[] original, int newLength)
  • public static T[] copyOf(T[] original, int newLength)
  • public static T[] copyOf(U[] original, int newLength, Class newType)

In these methods the arguments are,

Let us see demonstration of the copyOf() method of Arrays class.

import java.util.Arrays; public class ArrayTest < public static void main(String[] args) < // original array int[] arr = ; System.out.println("Original array = " + Arrays.toString(arr)); // Example1 int[] newArray1 = Arrays.copyOf(arr, 3); System.out.println("NewArray1 = " + Arrays.toString(newArray1)); // Example2 int[] newArray2 = Arrays.copyOf(arr, 5); System.out.println("NewArray2 = " + Arrays.toString(newArray2)); // Example3 int[] newArray3 = Arrays.copyOf(arr, 7); System.out.println("NewArray3 = " + Arrays.toString(newArray3)); > >

Original array = [10, 20, 30, 40, 50]NewArray1 = [10, 20, 30]NewArray2 = [10, 20, 30, 40, 50]NewArray3 = [10, 20, 30, 40, 50, 0, 0]

How these different outputs are coming? To understand these, we need to see how copyOf() method of the Arrays class is implemented?

How Arrays.copyOf() is implemented?

Whenever we call Arrays.copyOf(arr, newLength) then,

a) One local array variable is created with the size of passed length “newLength”
b) Then it internally calls System.arraycopy() method
c) Return the copied array

The source code for the copyOf() method with int [] array is given as,

public static int[] copyOf(int[] original, int newLength)

All the overloaded forms of Arrays.copyOf() method is implemented in a similar way. In System.arraycopy() method we have seen that the last argument was a length. The Arrays.copyOf() method internally finds the minimum value between original array length and newLength.

If newLength is minimum compared to the length of the original array then, only that portion of array elements will be copied from the original array. Example:-

// original array int[] arr = ; // new array int[] newArray = Arrays.copyOf(arr, 3); System.out.println(Arrays.toString(newArray));

The length of the original array arr is 5, see how to find the length of the Java array. We want to copy only 3 elements therefore we are calling Arrays.copyOf(arr, 3); Internally this method we will find Math.min(5, 3) => 3, and since 3 is lesser between 5 and 3, therefore, it will call System.arraycopy(arr, 0, copy, 0, 3); Only three-element will copied to the temporary array, and returned to the caller method.

Читайте также:  Optimistic lock in java

But if the original array length is minimum compared to the newLength then the remaining elements will be filled by default values. Let us see it through an example,

// original array int[] arr = ; // new array int[] newArray = Arrays.copyOf(arr, 7); System.out.println(Arrays.toString(newArray));
  • One copy [] will be created with length 7. Since it is array creation with default value therefore the copy array will holds [0, 0, 0, 0, 0, 0, 0] because 0 is default value of int data type.
  • Now, it calls System.arraycopy(arr, 0, copy, 0, 5), and all five elements of the original array will be copied to copy [] .
  • The remaining 2 elements will remain as it is.

Examples to Copy Double and Char array using Arrays.copyOf()

// double array double[] doubleArr = ; System.out.println("Double Array = " + Arrays.toString(doubleArr)); // copy array double[] arr1 = Arrays.copyOf(doubleArr, 3); System.out.println("Arr1 = " + Arrays.toString(arr1)); double[] arr2 = Arrays.copyOf(doubleArr, doubleArr.length); System.out.println("Arr2 = " + Arrays.toString(arr2)); double[] arr3 = Arrays.copyOf(doubleArr, 7); System.out.println("Arr3 = " + Arrays.toString(arr3));

Double Array = [10.5, 15.9, 500.0, -88888.0, 0.9]Arr1 = [10.5, 15.9, 500.0]Arr2 = [10.5, 15.9, 500.0, -88888.0, 0.9]Arr3 = [10.5, 15.9, 500.0, -88888.0, 0.9, 0.0, 0.0]

// char array char[] charArr = ; System.out.println("Char Array = " + Arrays.toString(charArr)); // copy array char[] arr1 = Arrays.copyOf(charArr, 4); System.out.println("Arr1 = " + Arrays.toString(arr1)); char[] arr2 = Arrays.copyOf(charArr, charArr.length); System.out.println("Arr2 = " + Arrays.toString(arr2)); char[] arr3 = Arrays.copyOf(charArr, 15); System.out.println("Arr3 = " + Arrays.toString(arr3));

Char Array = [K, n, o, w, P, r, o, g, r, a, m]Arr1 = [K, n, o, w]Arr2 = [K, n, o, w, P, r, o, g, r, a, m]Arr3 = [K, n, o, w, P, r, o, g, r, a, m,

Additional Points

  • The copyOf() method with all its overloaded forms was introduced in Java 1.6 version.
  • This method throws NullPointerException if the passed original array is null. Therefore, it is better to check if(original != null) and then call copyOf().
  • It also throws NegativeArraySizeException if the passed length (i.e. newLength) is negative.
import java.util.Arrays; public class ArrayTest < public static void main(String[] args) < int[] arr = null; int[] newArray1 = Arrays.copyOf(arr, 3); >>

Exception in thread “main” java.lang.NullPointerException: Cannot read the array length because “original” is null
at java.base/java.util.Arrays.copyOf(Arrays.java:3585)
at ArrayTest.main(ArrayTest.java:5)

import java.util.Arrays; public class ArrayTest < public static void main(String[] args) < int[] arr = null; int[] newArray1 = Arrays.copyOf(arr, -3); >>

Exception in thread “main” java.lang.NegativeArraySizeException: -3
at java.base/java.util.Arrays.copyOf(Arrays.java:3584)
at ArrayTest.main(ArrayTest.java:5)

Copy Multidimensional Array using copyOf() of Java Arrays

The Arrays.copyOf() method also can be used to copy the Java multidimensional array like 2D Java array and 3D Java array.

Читайте также:  Текст

Java program to find the copy of two dimensional (2D) Java array using Arrays.copyof() method,

import java.util.Arrays; public class ArrayTest < public static void main(String[] args) < // original 2D array 3x2 int matrix[][] = < < 1, 2 >, < 4, 5 >, < 7, 8 >>; System.out.println("Original = " + Arrays.deepToString(matrix)); // Example1 int[][] newMatrix1 = Arrays.copyOf(matrix, 1); System.out.println("newMatrix1 = " + Arrays.deepToString(newMatrix1)); // Example2 int[][] newMatrix2 = Arrays.copyOf(matrix, 3); System.out.println("newMatrix2 = " + Arrays.deepToString(newMatrix2)); // Example3 int[][] newMatrix3 = Arrays.copyOf(matrix, 5); System.out.println("newMatrix3 = " + Arrays.deepToString(newMatrix3)); > >

Original = [[ 1, 2 ], [ 4, 5 ], [ 7, 8 ]]
newMatrix1 = [[ 1, 2 ]]
newMatrix2 = [[ 1, 2 ], [ 4, 5 ], [ 7, 8 ]]
newMatrix3 = [[ 1, 2 ], [ 4, 5 ], [ 7, 8 ] , null, null ]

Java program to find the copy of three dimensional (3D) Java array using Arrays.copyof() method,

import java.util.Arrays; public class ArrayTest < public static void main(String[] args) < // 3D array 2x3x2 int[][][] arr = ,,>,,,>>; System.out.println("Original = " + Arrays.deepToString(arr)); // Example1 int[][][] newArr1 = Arrays.copyOf(arr, 1); System.out.println("newArr1 = " + Arrays.deepToString(newArr1)); // Example2 int[][][] newArr2 = Arrays.copyOf(arr, 2); System.out.println("newArr2 = " + Arrays.deepToString(newArr2)); // Example3 int[][][] newArr3 = Arrays.copyOf(arr, 4); System.out.println("newArr3 = " + Arrays.deepToString(newArr3)); > >

Original = [[[ 1, 2 ], [ 3, 4 ], [ 5, 6 ]], [[ 7, 8 ], [ 9, 1 ], [2, 3 ]]]
newArr1 = [[[ 1, 2 ], [ 3, 4 ], [ 5, 6 ]]]
newArr2 = [[[ 1, 2 ], [ 3, 4 ], [ 5, 6 ]], [[ 7, 8 ], [ 9, 1 ], [2, 3 ]]]
newArr3 = [[[ 1, 2 ], [ 3, 4 ], [ 5, 6 ]], [[ 7, 8 ], [ 9, 1 ], [2, 3 ]] , null, null ]

Copy Array of Objects

Using the Arrays.copyOf() method, we can also copy the array of objects. It is very similar to the previous programs. In the Arrays.toString() method, we have discussed how to display an array of objects we will use that concept.

class Student private int idNum; 
private String name;

// constructor
public Student(int idNum, String name) this.idNum = idNum;
this.name = name;
>

@Override
public String toString() return "[" + idNum + ", " + name + "]";
>
>
import java.util.Arrays; public class Collage < public static void main(String[] args) < // array of Student objects Student[] st = new Student[3]; // initialize Student object st[0] = new Student(100, "Emma"); st[1] = new Student(115, "Alex"); st[2] = new Student(225, "Amelia"); // display Student details (Original) System.out.println("Array = " + Arrays.toString(st)); // Example1:- copy only first Student objects Student[] st1 = Arrays.copyOf(st, 1); // display new array System.out.println("St1 = " + Arrays.toString(st1)); // Example2:- copy all Student objects Student[] st2 = Arrays.copyOf(st, st.length); // display new array System.out.println("St2 = " + Arrays.toString(st2)); // Example3:- copy more then 3 Student objects Student[] st3 = Arrays.copyOf(st, 5); // display new array System.out.println("St3 = " + Arrays.toString(st3)); >>

Array = [[ 100, Emma ], [ 115, Alex ], [ 225, Amelia ]]
St1 = [[ 100, Emma ]]
St2 = [[ 100, Emma ], [ 115, Alex ], [ 225, Amelia ]]
St3 = [[ 100, Emma ], [ 115, Alex ], [ 225, Amelia ] , null, null ]

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Источник

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