Skip to content

Commit 32c119b

Browse files
author
Michael Kabatek
committed
Added Array cloning test to demo copying a reference
to and object versus cloning/copying the object
1 parent eb5bc00 commit 32c119b

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

ArrayCloneTest/ArrayCloneTest.java

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import java.util.Arrays;
2+
3+
public class ArrayCloneTest {
4+
5+
//Private Member Variables
6+
static String myString = "Hello, World";
7+
static int[] data = {2, 3, 4, 5, 6, 7};
8+
static int[] backup;
9+
10+
11+
private static void printStuff(String inputString){
12+
13+
System.out.println(inputString);
14+
15+
}
16+
17+
public static void main(String[ ] args) {
18+
19+
20+
21+
printStuff("data: " + Arrays.toString(data));
22+
printStuff("Assign data's reference to backup");
23+
printStuff("backup = data;");
24+
backup = data;
25+
26+
printStuff("backup now contains a reference/alias to the data variable ...");
27+
28+
printStuff("changing value in data: data[2] = 10;");
29+
data[2] = 10;
30+
printStuff("data: " + Arrays.toString(data));
31+
printStuff("backup: " + Arrays.toString(backup));
32+
33+
printStuff("!!! Notice Both Arrays Changed !!!");
34+
35+
36+
printStuff("");
37+
printStuff("## Reset variables ##");
38+
printStuff("");
39+
data = new int[] {2, 3, 4, 5, 6, 7};
40+
backup = new int[] {};
41+
42+
printStuff("data: " + Arrays.toString(data));
43+
printStuff("clone data to backup to make a copy");
44+
printStuff("backup = data.clone();");
45+
backup = data.clone();
46+
47+
printStuff("COPY data to new variable backup using .clone()...");
48+
49+
printStuff("changing value in data: data[2] = 10;");
50+
data[2] = 10;
51+
printStuff("data: " + Arrays.toString(data));
52+
printStuff("backup: " + Arrays.toString(backup));
53+
printStuff("!!! Notice only data Array Changed !!!");
54+
55+
56+
}
57+
58+
}

0 commit comments

Comments
 (0)