/* * [TestArraycopy.java] * * Summary: Methods to demonstrate the various ways of copying an array. * * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 2006-03-24 */ package com.mindprod.example; import java.util.Arrays; import static java.lang.System.*; /** * Methods to demonstrate the various ways of copying an array. *

* * @author Roedy Green, Canadian Mind Products * @version 1.0 2006-03-24 * @noinspection WeakerAccess * @since 2006-03-24 */ public final class TestArraycopy { /** * 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 out.println( ">>>planets1" ); for ( String planet : planets1 ) { 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 out.println( ">>>planets2" ); for ( String planet : planets2 ) { out.println( planet ); } // copy with Arrays.copyOf, JDK 1.8+ only String[] planets3 = Arrays.copyOf( planets, planets.length ); // display result to make sure item worked out.println( ">>>planets3" ); for ( String planet : planets3 ) { out.println( planet ); } // copy with Arrays.copyRangeOf, JDK 1.8+ only String[] planets4 = Arrays.copyOfRange( planets, 0 /* from */, planets.length /* to+1 */ ); // display result to make sure item worked out.println( ">>>planets4" ); for ( String planet : planets4 ) { out.println( planet ); } } }