package com.mindprod.example;

import java.util.Arrays;

/**
 * Methods to demonstrate the various ways of copying an array.
 * <p/>
 * composed with IntelliJ IDEA
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.0, 2006-03-24.
 * @noinspection WeakerAccess
 */
public final class TestArraycopy
    {
// --------------------------- main() method ---------------------------

    /**
     * Sample code to copy arrays four different ways.
     *
     * @param args not used.
     * @noinspection ManualArrayCopy
     */
    public static void main( String[] args )
        {
        // create an array of 9 Strings
        final String[] planets = {
                "Mercury",
                "Venus",
                "Earth",
                "Mars",
                "Jupiter",
                "Saturn",
                "Uranus",
                "Neptune",
                "Pluto" };

        // manual copy
        String[] planets1 = new String[planets.length];
        for ( int i = 0; i < planets.length; i++ )
            {
            planets1[ i ] = planets[ i ];
            }
        // display result to make sure item worked
        System.out.println( ">>>planets1" );
        for ( String planet : planets1 )
            {
            System.out.println( planet );
            }

        // Copy using System.arrayCopy
        String[] planets2 = new String[planets.length];
        System.arraycopy( planets, 0, planets2, 0, planets.length );
        // display result to make sure item worked
        System.out.println( ">>>planets2" );
        for ( String planet : planets2 )
            {
            System.out.println( planet );
            }

        // copy with Arrays.copyOf, JDK 1.6+ only
        String[] planets3 = Arrays.copyOf( planets, planets.length );
        // display result to make sure item worked
        System.out.println( ">>>planets3" );
        for ( String planet : planets3 )
            {
            System.out.println( planet );
            }

        // copy with Arrays.copyRangeOf, JDK 1.6+ only
        String[] planets4 = Arrays.copyOfRange( planets, 0
                /* from */, planets.length
                /* to+1 */ );
        // display result to make sure item worked
        System.out.println( ">>>planets4" );
        for ( String planet : planets4 )
            {
            System.out.println( planet );
            }
        }
    }