logo

Array Copy Java

Kun taulukko on annettu, meidän on kopioitava sen elementit eri matriisiin, naiiville käyttäjälle tulee mieleen alla oleva tapa, joka on kuitenkin virheellinen, kuten alla on kuvattu seuraavasti:

// 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;>

Lähtö:



Lähtöselitys: Kun teemme b = a, annamme itse asiassa viittauksen taulukkoon. Näin ollen, jos teemme muutoksia yhteen taulukkoon, se heijastuisi myös muihin matriisiin, koska sekä a että b viittaavat samaan paikkaan. Voimme myös varmistaa sen alla olevan koodin avulla seuraavasti:

Esimerkki:



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] + ' '); } }>

>

>

Lähtö

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

Menetelmät:

Olemme nähneet sisäisen työn kopioitaessa elementtejä ja reunatapauksia, jotka on otettava huomioon yllä luotujen virheiden läpikäymisen jälkeen, joten voimme nyt ehdottaa oikeita tapoja kopioida taulukko seuraavasti:

  1. Iteroidaan kunkin alkuperäisen taulukon elementti ja kopioidaan yksi elementti kerrallaan
  2. Clone()-menetelmän käyttäminen
  3. Käytä arraycopy()-menetelmää
  4. Arrays-luokan copyOf()-menetelmällä
  5. Arrays-luokan copyOfRange()-menetelmän käyttäminen

Tapa 1: Iteroidaan kunkin alkuperäisen taulukon elementti ja kopioidaan yksi elementti kerrallaan. Tätä menetelmää käytettäessä se takaa, että b:n muutokset eivät muuta alkuperäistä taulukkoa a, kuten alla olevassa esimerkissä esitetään seuraavasti:

Esimerkki:

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] + ' '); } }>

>

>

Lähtö

ero $ ja $$ välillä
Contents of a[] 1 8 3 Contents of b[] 2 8 3>

Tapa 2: Käyttämällä Clone()-menetelmää

Edellisessä menetelmässä meidän piti iteroida koko taulukko kopioidaksemme, voimmeko tehdä paremmin? Kyllä, voimme käyttää kloonimenetelmää Javassa.

Esimerkki:

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] + ' '); } }>

>

>

Lähtö

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

Tapa 3: Käytä arraycopy()-menetelmää

Voimme myös käyttää System.arraycopy() Menetelmä. Järjestelmä on java.lang-paketissa. Sen allekirjoitus on seuraava:

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

Parametrit:

  • src tarkoittaa lähdetaulukkoa.
  • srcPos on hakemisto, josta kopiointi alkaa.
  • alkaa tarkoittaa kohderyhmää
  • destPos on indeksi, josta kopioidut elementit sijoitetaan kohdetaulukkoon.
  • pituus on kopioitavan aliryhmän pituus.

Esimerkki:

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] + ' '); } }>

>

>

Lähtö

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

Tapa 4: Arrays-luokan copyOf()-menetelmällä

Jos haluamme kopioida taulukon ensimmäiset elementit tai koko kopion taulukosta, voit käyttää tätä menetelmää.

Syntaksi:

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

Parametrit:

  • Alkuperäinen sarja
  • Kopioitavan taulukon pituus.

Esimerkki:

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] + ' '); } }>

>

>

Lähtö

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

Menetelmä 5: Arrays-luokan copyOfRange()-menetelmän käyttäminen

Tämä menetelmä kopioi määritetyn taulukon määritetyn alueen uudeksi taulukoksi.

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

Parametrit:

  • Alkuperäinen matriisi, josta alue kopioidaan
  • Kopioitavan alueen alkuperäinen indeksi
  • Kopioitavan alueen lopullinen indeksi, poissulkeva

Esimerkki:

Java




// 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] + ' '); } }>

alleviivaus alas

>

>

Lähtö

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

Lopuksi keskustellaan asiasta yleiskatsaus yllä oleviin menetelmiin:

  • Pelkkä viitteiden antaminen on väärin
  • Taulukko voidaan kopioida iteroimalla taulukon yli ja määrittämällä elementtejä yksitellen.
  • Voimme välttää elementtien iteroinnin käyttämällä clone() tai System.arraycopy()
  • clone() luo uuden samankokoisen taulukon, mutta System.arraycopy() voidaan käyttää kopioimaan lähdealueelta kohdealueelle.
  • System.arraycopy() on nopeampi kuin clone(), koska se käyttää Java Native Interfacea
  • Jos haluat kopioida taulukon ensimmäiset elementit tai kokonaisen kopion taulukosta, voit käyttää Arrays.copyOf()-menetelmää.
  • Arrays.copyOfRange() -funktiota käytetään taulukon tietyn alueen kopioimiseen. Jos aloitusindeksi ei ole 0, voit käyttää tätä menetelmää osittaisen taulukon kopioimiseen.