-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCopyOfTest.java
63 lines (57 loc) · 2 KB
/
CopyOfTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package arrays;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* This program demonstrates the use of reflection for manipulating arrays.
*
* @author Cay Horstmann
* @version 1.2 2012-05-04
*/
public class CopyOfTest {
public static void main(String[] args) {
int[] a = {1, 2, 3};
a = (int[]) goodCopyOf(a, 10);
System.out.println(Arrays.toString(a));
String[] b = {"Tom", "Dick", "Harry"};
b = (String[]) goodCopyOf(b, 10);
System.out.println(Arrays.toString(b));
/*
System.out.println("The following call will generate an exception.");
b = (String[]) badCopyOf(b, 10);
*/
}
/**
* This method attempts to grow an array by allocating a new array and copying all elements.
*
* @param a the array to grow
* @param newLength the new length
* return a larger array that contains all elements of a. However, the returned array has
* type ObjectQ , not the same type as a
*/
/*
@NotNull
private static Object badCopyOf(Object a, int newLength) {
Object[] newArray = new Object[newLength];
System.arraycopy(a, 0, newArray, 0, Math.min(a.length, newLength)); // not useful
return newArray;
}
*/
/**
* This method grows an array by allocating a new array of the same type and
* copying all elements.
*
* @param a the array to grow. This can be an object array or a primitive
* type array
* @return a larger array that contains all elements of a.
*/
private static Object goodCopyOf(Object a, int newLength) {
Class cl = a.getClass();
if (!cl.isArray())
return null;
Class componentType = cl.getComponentType();
int length = Array.getLength(a);
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, Math.min(length, newLength));
return newArray;
}
}