Connecting Tech Pros Worldwide Forums | Help | Site Map

array data type conversion

Newbie
 
Join Date: Jul 2007
Location: western US
Posts: 10
#1: Aug 24 '09
I have a float[] array, which I need to convert to a Double[] array. The task does not seem as trivial as I expected it to be. Can anyone give me some guidance?

JosAH's Avatar
Expert
 
Join Date: Mar 2007
Posts: 10,611
#2: Aug 25 '09

re: array data type conversion


Quote:

Originally Posted by ElderGeek View Post

I have a float[] array, which I need to convert to a Double[] array. The task does not seem as trivial as I expected it to be. Can anyone give me some guidance?

You have to do it element by element and store the new elements in your new array. e.g.

Expand|Select|Wrap|Line Numbers
  1. Double[] convert(float[] f) {
  2.  
  3.    Double[] d= new Double[f.length];
  4.    for (int i= 0; i < f.length; i++)
  5.       d[i]= new Double(f); // convert any way you like
  6.    return d;
  7. }
  8.  
Arrays of type D can't be cast to an array of type B, not even when type D extends type B (a D 'is a' B). Here is a small example that shows why you can't do it:

Expand|Select|Wrap|Line Numbers
  1. public class Animal { ... }
  2. public class Poodle extends Animal { ... }
  3. public class Lion extends Animal { ... }
  4.  
  5. Poodle[] poodles = { /* cute little poodles in here */ };
  6. Animal[] animals= (Animal[])poodles; // this is not allowed because:
  7. animals[0]= new Lion(); // the poodles won't survive ;-)
  8.  
kind regards,

Jos
Newbie
 
Join Date: Jul 2007
Location: western US
Posts: 10
#3: Aug 25 '09

re: array data type conversion


Nice and concise -- thanks!
Reply

Tags
array