Re: Customize toString() for arrays...?
markspace wrote:
markspace wrote:
Hmm.... I might want to do that...
This seems to work:
package test;
import java.lang.reflect.Array;
public class Util {
static public <T extends Number> T[] autoBox( Class<T> type,
Object array )
{
int length = Array.getLength( array );
Object retVal = Array.newInstance( type, length );
for( int i = 0; i < length; i++ ) {
Array.set( retVal, i, Array.get( array, i) );
}
return (T[])retVal;
}
}
Useage:
public static void main( String[] args )
{
int[] test = {1,2,3};
System.out.println( Arrays.asList( autoBox( Integer.class, test ) ) );
}
prints:
[1, 2, 3]
Oh, I see the problem now...
import java.util.Arrays;
public class AsList {
public static void main(String[] args) {
Integer[] boxes = { 1, 2, 3 };
int[] primitives = { 1, 2, 3 };
System.out.println(Arrays.asList(boxes));
System.out.println(Arrays.asList(primitives));
}
}
[alan@postojna ~]$ javac AsList.java
[alan@postojna ~]$ java AsList
[1, 2, 3]
[[I@10d448]
Nice solution, Mark Space. I looked into removing the unsafe array cast,
but it appears as though it can't be helped.
--
Alan Gutierrez - alan@blogometer.com - http://twitter.com/bigeasy