Growing an Array

From Java Example Source Code

Jump to: navigation, search

Contents

[edit] Overview - Growing an Array

This Java example program introduce growing an Array.

[edit] Java Source Code

  • Package: example.array
  • File: ArrayGrowTest.java
  1. package example.array;
  2.  
  3. import java.lang.reflect.Array;
  4.  
  5. public class ArrayGrowTest {
  6.     public static void main(String[] args) {
  7. 	int[] a = { 1, 2, 3 };
  8. 	a = (int[]) arrayGrow(a);
  9. 	arrayPrint(a);
  10.     }
  11.  
  12.     static Object arrayGrow(Object a) {
  13. 	Class cl = a.getClass();
  14. 	if (!cl.isArray())
  15. 	    return null;
  16. 	Class componentType = a.getClass().getComponentType();
  17. 	int length = Array.getLength(a);
  18. 	int newLength = length + 10;
  19.  
  20. 	Object newArray = Array.newInstance(componentType, newLength);
  21. 	System.arraycopy(a, 0, newArray, 0, length);
  22. 	return newArray;
  23.     }
  24.  
  25.     static void arrayPrint(Object a) {
  26. 	Class cl = a.getClass();
  27. 	if (!cl.isArray())
  28. 	    return;
  29. 	Class componentType = a.getClass().getComponentType();
  30. 	int length = Array.getLength(a);
  31. 	System.out.println(componentType.getName() + "[" + length + "]");
  32. 	for (int i = 0; i < length; i++)
  33. 	    System.out.println(Array.get(a, i));
  34.     }
  35. }

[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.


Personal tools