471,896 Members | 1,722 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,896 software developers and data experts.

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 4988
11,448 Expert 8TB
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) {
  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. }
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 { ... }
  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 ;-)
kind regards,

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

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.