logo

Copia de matriz en Java

Dada una matriz, necesitamos copiar sus elementos en una matriz diferente; a un usuario ingenuo le viene a la mente el siguiente método, que sin embargo es incorrecto, como se muestra a continuación:

// Java Program to Illustrate Wrong Way Of Copying an Array // Input array int a[] = { 1, 8, 3 }; // Creating an array b[] of same size as a[] int b[] = new int[a.length]; // Doesn't copy elements of a[] to b[], only makes // b refer to same location b = a;>

Producción:



Explicación de salida: Cuando hacemos b = a, en realidad estamos asignando una referencia a la matriz. Por lo tanto, si realizamos algún cambio en una matriz, se reflejará también en otras matrices porque tanto a como b se refieren a la misma ubicación. También podemos verificarlo con el código que se muestra a continuación:

Ejemplo:

Java




// A Java program to demonstrate that simply> // assigning one array reference is incorrect> public> class> Test {> >public> static> void> main(String[] args)> >{> >int> a[] = {>1>,>8>,>3> };> > >// Create an array b[] of same size as a[]> >int> b[] =>new> int>[a.length];> > >// Doesn't copy elements of a[] to b[],> >// only makes b refer to same location> >b = a;> > >// Change to b[] will also reflect in a[]> >// as 'a' and 'b' refer to same location.> >b[>0>]++;> > >System.out.println(>'Contents of a[] '>);> >for> (>int> i =>0>; i System.out.print(a[i] + ' '); System.out.println(' Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }>

>

>

Producción

Contents of a[] 2 8 3 Contents of b[] 2 8 3>

Métodos:

Hemos visto el trabajo interno al copiar elementos y casos extremos que se deben tener en cuenta después de solucionar los errores generados anteriormente, por lo que ahora podemos proponer formas correctas de copiar una matriz como se enumera a continuación:

  1. Iterando cada elemento de la matriz original dada y copiando un elemento a la vez
  2. Usando el método clonar()
  3. Usando el método arraycopy()
  4. Usando el método copyOf() de la clase Arrays
  5. Usando el método copyOfRange() de la clase Arrays

Método 1: Iterando cada elemento de la matriz original dada y copiando un elemento a la vez. Con el uso de este método, se garantiza que cualquier modificación en b, no alterará la matriz original a, como se muestra en el siguiente ejemplo:

Ejemplo:

Java




// Java program to demonstrate copying by> // one by one assigning elements between arrays> > // Main class> public> class> GFG {> > >// Main driver method> >public> static> void> main(String[] args)> >{> >// Input array a[]> >int> a[] = {>1>,>8>,>3> };> > >// Create an array b[] of same size as a[]> >int> b[] =>new> int>[a.length];> > >// Copying elements of a[] to b[]> >for> (>int> i =>0>; i b[i] = a[i]; // Changing b[] to verify that // b[] is different from a[] b[0]++; // Display message only System.out.println('Contents of a[] '); for (int i = 0; i System.out.print(a[i] + ' '); // Display message only System.out.println(' Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }>

>

>

Producción

actriz zeenat aman
Contents of a[] 1 8 3 Contents of b[] 2 8 3>

Método 2: Usando el método Clonar()

En el método anterior tuvimos que iterar sobre toda la matriz para hacer una copia, ¿podemos hacerlo mejor? Sí, podemos usar el método de clonación en Java.

Ejemplo:

Java




// Java program to demonstrate Copying of Array> // using clone() method> > // Main class> public> class> GFG {> > >// Main driver method> >public> static> void> main(String[] args)> >{> >// Input array a[]> >int> a[] = {>1>,>8>,>3> };> > >// Copying elements of a[] to b[]> >int> b[] = a.clone();> > >// Changing b[] to verify that> >// b[] is different from a[]> >b[>0>]++;> > >// Display message for better readability> >System.out.println(>'Contents of a[] '>);> > >for> (>int> i =>0>; i System.out.print(a[i] + ' '); // Display message for better readability System.out.println(' Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }>

>

>

Producción

Contents of a[] 1 8 3 Contents of b[] 2 8 3>

Método 3: Usando el método arraycopy()

También podemos usar Sistema.arraycopy() Método. El sistema está presente en el paquete java.lang. Su firma es como:

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

Parámetros:

  • src denota la matriz de origen.
  • possrc es el índice desde el que comienza la copia.
  • comenzar denota la matriz de destino
  • destPos es el índice desde el cual se colocan los elementos copiados en la matriz de destino.
  • longitud es la longitud del subarreglo que se va a copiar.

Ejemplo:

Java




// Java program to demonstrate array> // copy using System.arraycopy()> > // Main class> public> class> GFG {> > >// Main driver method> >public> static> void> main(String[] args)> >{> >// Custom input array> >int> a[] = {>1>,>8>,>3> };> > >// Creating an array b[] of same size as a[]> >int> b[] =>new> int>[a.length];> > >// Copying elements of a[] to b[]> >System.arraycopy(a,>0>, b,>0>,>3>);> > >// Changing b[] to verify that> >// b[] is different from a[]> >b[>0>]++;> > >// Display message only> >System.out.println(>'Contents of a[] '>);> > >for> (>int> i =>0>; i System.out.print(a[i] + ' '); // Display message only System.out.println(' Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }>

>

>

Producción

Contents of a[] 1 8 3 Contents of b[] 2 8 3>

Método 4: Usando el método copyOf() de la clase Arrays

Si queremos copiar los primeros elementos de una matriz o una copia completa de la matriz, puede utilizar este método.

Sintaxis:

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

Parámetros:

  • matriz original
  • Longitud de la matriz que se va a copiar.

Ejemplo:

Java




// Java program to demonstrate array> // copy using Arrays.copyOf()> > // Importing Arrays class from utility class> import> java.util.Arrays;> > // Main class> class> GFG {> > >// Main driver method> >public> static> void> main(String[] args)> >{> >// Custom input array> >int> a[] = {>1>,>8>,>3> };> > >// Create an array b[] of same size as a[]> >// Copy elements of a[] to b[]> >int> b[] = Arrays.copyOf(a,>3>);> > >// Change b[] to verify that> >// b[] is different from a[]> >b[>0>]++;> > >System.out.println(>'Contents of a[] '>);> > >// Iterating over array. a[]> >for> (>int> i =>0>; i System.out.print(a[i] + ' '); System.out.println(' Contents of b[] '); // Iterating over array b[] for (int i = 0; i System.out.print(b[i] + ' '); } }>

>

>

Producción

Contents of a[] 1 8 3 Contents of b[] 2 8 3>

Método 5: Usando el método copyOfRange() de la clase Arrays

Este método copia el rango especificado de la matriz especificada en una nueva matriz.

public static int[] copyOfRange?(int[] original, int from, int to)>

Parámetros:

  • Matriz original de la que se va a copiar un rango
  • Índice inicial del rango a copiar
  • Índice final del rango a copiar, exclusivo

Ejemplo:

Java

verma dhanashree




// Java program to demonstrate array> // copy using Arrays.copyOfRange()> > // Importing Arrays class from utility package> import> java.util.Arrays;> > // Main class> class> GFG {> > >// Main driver method> >public> static> void> main(String[] args)> >{> >// Custom input array> >int> a[] = {>1>,>8>,>3>,>5>,>9>,>10> };> > >// Creating an array b[] and> >// copying elements of a[] to b[]> >int> b[] = Arrays.copyOfRange(a,>2>,>6>);> > >// Changing b[] to verify that> >// b[] is different from a[]> > >// Iterating over array a[]> >System.out.println(>'Contents of a[] '>);> >for> (>int> i =>0>; i System.out.print(a[i] + ' '); // Iterating over array b[] System.out.println(' Contents of b[] '); for (int i = 0; i System.out.print(b[i] + ' '); } }>

>

>

Producción

Contents of a[] 1 8 3 5 9 10 Contents of b[] 3 5 9 10>

Por último, analicemos la Descripción general de los métodos anteriores:

  • Simplemente asignar referencias es incorrecto
  • La matriz se puede copiar iterando sobre una matriz y asignando elementos uno por uno.
  • Podemos evitar la iteración sobre elementos. usando clone() o System.arraycopy()
  • clone() crea una nueva matriz del mismo tamaño, pero Sistema.arraycopy() se puede utilizar para copiar desde un rango de origen a un rango de destino.
  • System.arraycopy() es más rápido que clone() ya que utiliza la interfaz nativa de Java
  • Si desea copiar los primeros elementos de una matriz o una copia completa de una matriz, puede utilizar el método Arrays.copyOf().
  • Arrays.copyOfRange() se utiliza para copiar un rango específico de una matriz. Si el índice inicial no es 0, puede utilizar este método para copiar una matriz parcial.