Remember to check the "with heading" box in the lower right corner. Surround code listings with <pre> and </pre>, and if you use < and > symbols you must say & lt ; and & gt ;
2004/09/26 23:17 EST (via web):
Two points:
- When Neal suggested that you declare the array as an 'Object[]' then I think he meant that
repreturns an 'Object[]' not a 'T[]', thats my reading of his comments anyway. The reason is that you will be less surprised by theClassCastExceptionparticularly since the documentation presumably says that it returns an array of 'Object's and not 'T's. - The method suggested of using
java.lang.reflect.Array.newInstance( int )works OK for an array because all arrays have a one-argument constructor. However in general you can't rely on a type having a no-argument constructor, i.e.java.lang.Class.newInstance()might fail. The general solution is to make an abstract-instance-factory method inGenericArray, i.e. 'public abstract T[] instance( int size );', and thus makeGenericArrayabstract. Then to useGenericArrayyou must sub-class it and provide a correctly typed instance-factory method, for e.g.:abstract class GenericArray< T > { private final T[] array; public GenericArray( final int size ) { array = instance( size ); } public abstract T[] instance( final int size ); public void set( final int index, final T value ) { array[ index ] = value; } public T get( final int index ) { return array[ index ]; } public T[] getArray() { return array; } } public class IntegerArray extends GenericArray< Integer > { public IntegerArray( final int size ) { super( size ); } public Integer[] instance( final int size ) { return new Integer[ size ]; } public static void main( final String[] notUsed ) { final int size = 3; final IntegerArray ia = new IntegerArray( size ); for ( int i = 0; i < size; i++ ) ia.set( i, i ); for ( int i = 0; i < size; i++ ) System.out.print( ia.get( i ) + " " ); System.out.println(); final Integer[] pia = ia.getArray(); for ( int i = 0; i < size; i++ ) System.out.print( pia[ i ] + " " ); System.out.println(); } }
subtopics:
|