Growing an Array
From Java Example Source Code
Contents |
[edit] Overview - Growing an Array
This Java example program introduce growing an Array.
[edit] Java Source Code
- Package: example.array
- File: ArrayGrowTest.java
package example.array;
import java.lang.reflect.Array;
public class ArrayGrowTest {
public static void main(String[] args) {
int[] a = { 1, 2, 3 };
a = (int[]) arrayGrow(a);
arrayPrint(a);
}static Object arrayGrow(Object a) {
Class cl = a.getClass();
if (!cl.isArray())
return null;
Class componentType = a.getClass().getComponentType();
int length = Array.getLength(a);
int newLength = length + 10;
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, length);
return newArray;}static void arrayPrint(Object a) {
Class cl = a.getClass();
if (!cl.isArray())
return;Class componentType = a.getClass().getComponentType();
int length = Array.getLength(a);
System.out.println(componentType.getName() + "[" + length + "]");
for (int i = 0; i < length; i++)
System.out.println(Array.get(a, i));
}}
[edit] What Result You Can Get
Run the program, you will get:
int[13] 1 2 3 0 0 0 0 0 0 0 0 0 0
[edit] Required External Libraries and/or Files for this Java Example
Need nothing.
[edit] How to Run this Java Example Program
We recommend running this Java example program with Eclipse.
For assistance in working with Eclipse, please see How to Run Java Program with Eclipse.
It's fairly easy.
[edit] Question & Answer
Any question?
Click edit and post your question or answer here.
