package ArrayThangy;
import java.io.*;
public class Main
{
public Main (){}
public static class ArrayThangy
{
public int[] theGoodies = {1, 2, 3};
public ArrayThangy (){}
}
public static void main (String args [])
{
ArrayThangy numeroUno = new ArrayThangy ();
ArrayThangy numeroDos = new ArrayThangy ();
ArrayThangy numeroTres = new ArrayThangy ();
System.out.println ("Assign array one to array two");
// The following will result in a shallow copy, a reference
numeroDos = numeroUno;
System.out.println ("Note that the arrays are identical");
System.out.print ("Array one: ");
for (int i = 0; i < numeroUno.theGoodies.length; i++)
{
System.out.print (numeroUno.theGoodies [i]);
System.out.print (" ");
}
System.out.print ("\nArray two: ");
for (int i = 0; i < numeroDos.theGoodies.length; i++)
{
System.out.print (numeroDos.theGoodies [i]);
System.out.print (" ");
}
System.out.println ("\n\nChange the value of an element in array two");
numeroDos.theGoodies [0] = 5;
System.out.println ("Note that the arrays are still identical");
System.out.print ("Array one: ");
for (int i = 0; i < numeroUno.theGoodies.length; i++)
{
System.out.print (numeroUno.theGoodies [i]);
System.out.print (" ");
}
System.out.print ("\nArray two: ");
for (int i = 0; i < numeroDos.theGoodies.length; i++)
{
System.out.print (numeroDos.theGoodies [i]);
System.out.print (" ");
}
System.out.println ("\n\nMake a deep copy of one to three");
// The following will result in a deep copy
for (int i = 0; i < numeroUno.theGoodies.length; i++)
numeroTres.theGoodies [i] = numeroUno.theGoodies [i];
System.out.println ("Note that arrays one and three are also identical");
System.out.print ("Array one: ");
for (int i = 0; i < numeroUno.theGoodies.length; i++)
{
System.out.print (numeroUno.theGoodies [i]);
System.out.print (" ");
}
System.out.print ("\nArray three: ");
for (int i = 0; i < numeroTres.theGoodies.length; i++)
{
System.out.print (numeroTres.theGoodies [i]);
System.out.print (" ");
}
System.out.println ("\nChange the value of an element in array three");
numeroTres.theGoodies [0] = 1;
System.out.println ("Note that the arrays are NOT identical");
System.out.print ("Array one: ");
for (int i = 0; i < numeroUno.theGoodies.length; i++)
{
System.out.print (numeroUno.theGoodies [i]);
System.out.print (" ");
}
System.out.print ("\nArray three: ");
for (int i = 0; i < numeroTres.theGoodies.length; i++)
{
System.out.print (numeroTres.theGoodies [i]);
System.out.print (" ");
}
}
}
Quote:
|
Originally Posted by Output
compile:
run:
Assign array one to array two
Note that the arrays are identical
Array one: 1 2 3
Array two: 1 2 3
Change the value of an element in array two
Note that the arrays are still identical
Array one: 5 2 3
Array two: 5 2 3
Make a deep copy of one to three
Note that arrays one and three are also identical
Array one: 5 2 3
Array three: 5 2 3
Change the value of an element in array three
Note that the arrays are NOT identical
Array one: 5 2 3
Array three: 1 2 3
|