FileDocCategorySizeDatePackage
ArrayDemo.javaAPI DocExample3165Sun Dec 14 22:47:40 GMT 2003oreilly.hcj.reflection

ArrayDemo

public class ArrayDemo extends Object
Demonstrates the use of the Array class.
author
Robert Simmons jr. (kraythe)
version
$Revision$

Fields Summary
Constructors Summary
Methods Summary
public static java.lang.ObjectcopyArray(java.lang.Object input)
Copy an array and return the copy.

param
input The array to copy.
return
The coppied array.
throws
IllegalArgumentException If input is not an array.

		final Class type = input.getClass();
		if (!type.isArray()) {
			throw new IllegalArgumentException();
		}
		final int length = Array.getLength(input);
		final Class componentType = type.getComponentType();

		final Object result = Array.newInstance(componentType, length);
		for (int idx = 0; idx < length; idx++) {
			Array.set(result, idx, Array.get(input, idx));
		}
		return result;
	
public static voidmain(java.lang.String[] args)
Run the demo.

param
args Command line arguments (ignored).

		try {
			int[] x = new int[] { 2, 3, 8, 7, 5 };
			char[] y = new char[] { 'a", 'z", 'e" };
			String[] z = new String[] { "Jim", "John", "Joe" };

			System.out.println(" -- x and y --");
			outputArrays(x, y);

			System.out.println(" -- x and copy of x --");
			outputArrays(x, copyArray(x));

			System.out.println(" -- y and copy of y --");
			outputArrays(y, copyArray(y));

			System.out.println(" -- z and copy of z --");
			outputArrays(z, copyArray(z));
		} catch (final Exception ex) {
			ex.printStackTrace();
		}
	
public static voidoutputArrays(java.lang.Object first, java.lang.Object second)
Print out 2 arrays in columnar format.

param
first The array for the first column.
param
second The array for the second column.
throws
IllegalArgumentException __UNDOCUMENTED__

		if (!first.getClass()
		          .isArray()) {
			throw new IllegalArgumentException("first is not an array.");
		}
		if (!second.getClass()
		           .isArray()) {
			throw new IllegalArgumentException("second is not an array.");
		}

		final int lengthFirst = Array.getLength(first);
		final int lengthSecond = Array.getLength(second);
		final int length = Math.max(lengthFirst, lengthSecond);

		for (int idx = 0; idx < length; idx++) {
			System.out.print("[" + idx + "]\t");
			if (idx < lengthFirst) {
				System.out.print(Array.get(first, idx) + "\t\t");
			} else {
				System.out.print("\t\t");
			}
			if (idx < lengthSecond) {
				System.out.print(Array.get(second, idx) + "\t");
			}
			System.out.println();
		}