Java Reference
In-Depth Information
System.out.println("int[][][] dimension is " + getArrayDimension(intArray));
}
public static int getArrayDimension(Object array) {
int dimension = 0;
Class c = array.getClass();
// Perform a check that the object is really an array
if (!c.isArray()) {
throw new IllegalArgumentException("Object is not an array");
}
while (c.isArray()) {
dimension++;
c = c.getComponentType();
}
return dimension;
}
}
int[][][] dimension is 3
Expanding an Array
An array in Java is a fixed-length data structure. That is, once you create an array, its length is fixed. The statement
“An array in Java is a fixed length data structure” is always true. You can create an array of a bigger size and copy the
old array elements to the new one at runtime. The Java collection classes such as ArrayList apply this technique
to let you add elements to the collection without worrying about its length. You can use the combination of the
getComponentType() method of the Class class and the newInstance() method of the Array class to create a new
array of a type. When you have the new array created, you can use the arraycopy() static method of the System class
to copy the old array elements to the new array. Listing 3-18 illustrates how to create an array of a particular type using
reflection. All runtime checks have been left out of the code for clarity.
Listing 3-18. Expanding an Array Using Reflection
// ExpandingArray.java
package com.jdojo.reflection;
import java.lang.reflect.Array;
import java.util.Arrays;
public class ExpandingArray {
public static void main(String[] args) {
// Create an array of length 2
int[] ids = {101, 102};
System.out.println("Old array length: " + ids.length);
System.out.println("Old array elements:" + Arrays.toString(ids));
// Expand the array by 1
ids = (int[]) expandBy(ids, 1);
 
Search WWH ::




Custom Search