469,326 Members | 1,452 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,326 developers. It's quick & easy.

array data type conversion

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?
Aug 24 '09 #1
2 4905
JosAH
11,448 Expert 8TB
@ElderGeek
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
Aug 25 '09 #2
Nice and concise -- thanks!
Aug 25 '09 #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

8 posts views Thread by chessc4c6 | last post: by
11 posts views Thread by x-pander | last post: by
204 posts views Thread by Alexei A. Frounze | last post: by
10 posts views Thread by Christian Christmann | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by harlem98 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.