Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

java.util.Arrays.copyOfRange() problem

Gen.JavaMar 30 2008 — edited Apr 1 2008

I need to convert primitive array (ex. int[].class) to its wrapper array (ex. Integer[].class). java.util.Arrays.copyOfRange() (in Java 1.6) produces a classCastException.
So, I had to develop my own version of java.util.Arrays.copyOfRange() as follows:

private static Object CopyOfRange (

Object Source[],

Class ArrayCompType )

{

Object Obj;

Obj = java.lang.reflect.Array.newInstance ( ArrayCompType,Source.length );

for ( int i=0; i < Source.length; i++ )

if ( Source[i] != null )

try {

java.lang.reflect.Array.set ( Obj,i,Source[i] );

}

catch ( Exception e )

{

return null;

}

return Obj;

}
This method converts any array to the new type except when you call it with:

int i[]={1,2,3};

Object[] o;

o=(Object[])CopyOfRange(i,Object.class);
this does not even compile because i is a primitive array and cannot be casted to Object array.


I thought of using Class.cast(), but couldn't get the syntax right

Thank you

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 29 2008
Added on Mar 30 2008
5 comments
661 views