Quicker way to cast array items?

Quicker way to cast array items?

Post by Paul Chapm » Mon, 21 Feb 2005 20:16:30


I have

Object[] array;

I happen to know that each of the items of the array has class MyClass. I
realize that I can't cast the whole array thus:

(MyClass[]) array

But is there a quicker way than copying the whole array into a new
MyClass[], casting the items one at a time?

TIA.

Cheers, Paul
 
 
 

Quicker way to cast array items?

Post by Anthony Bo » Mon, 21 Feb 2005 21:00:42


Use:

Object[] srcArray =
new MyClass[]{null, null, null, null};

MyClass[] targetArray =
new MyClass[srcArray.length];

System.arraycopy(srcArray, 0, targetArray, 0,
srcArray.length);

I hope this helps.

Anthony Borla

 
 
 

Quicker way to cast array items?

Post by Paul Chapm » Mon, 21 Feb 2005 22:17:04

Anthony,


Not quite copy-free, but better than a for-loop. And it worked. Thanks.

Cheers, Paul
 
 
 

Quicker way to cast array items?

Post by Aleksander » Mon, 21 Feb 2005 22:32:42


If you have srcArray
Object[] srcArray =
new MyClass[]{null, null, null, null};
you can just cast it:
MyClass[] targetArray = (MyClass[]) srcArray;

Copying is required if srcArray is created like tihs:
Object[] srcArray = new Object[]{null};

--
Regards, Olek
 
 
 

Quicker way to cast array items?

Post by Anthony Bo » Tue, 22 Feb 2005 11:19:39


Indeed, I should think *very significantly better* than a 'for' loop ;) !


More than glad to help get the job done :) !

Cheers,

Anthony Borla