Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping a double[] to a Double[]

Tags:

java

I am really new to java. I have come up to something I really can't get my head around. I understand that Double is a wrapper class and that you can wrap a double value inside an object of the said class. So a code looking something like this would work fine

double pi = 3.14;
Double tempVariable = new Double(pi);

So it seemed perfectly logical to me that since I can wrap a double to a Double, it would be as easy to wrap a double[] to a Double[]. But this isn't the case. I tried everything I could think of (syntax alterations - creating an object of type Object containing the said double[] and then casting to Double[], dealing with the Double object as if it was an array) but none of these worked.

I am using j2me.

Do you guys have any suggestions?

@MightyPork : That was the first thing I tried to do. The code I think, tries to do this is the following:

public Double[] modelWeights = new Double[9];
modelweights = {-1.31,1.39,-0.36,1.55,1.55,-2.03,2.25,2.27,-0.72};

But this won't work. I have no idea why.

@Abimaran Kugathasan:: I saw ArrayUtils yesterday and it would be a great solution but I am using j2me and classes such as List or HashSet (that are required for ArrayUtils) are not implemented in j2me. Am I missing something?

EDIT:: The thread linked by Abimaran Kugathasan had indeed other answers pretty close to fge's answer. Thank you all for the comments.

like image 318
Silas Avatar asked Oct 20 '22 18:10

Silas


1 Answers

Welcome to one of Java's historical baggage, arrays.

What happens is that similarly to the fact that you have primitive types double and their "class equivalent" Double, and that you can use one seamlessly for the other is because (since Java 5) in this case the compiler does boxing/unboxing for you.

But it won't do so for arrays; so Double[] is not a "wrapper class" for double[].

If you have a double[] array which you want to "turn into" a Double[], you have no choice but to copy yourself... For instance:

final double[] primitiveArray = ...;

final int len = primitiveArray.length;

final Double[] boxedArray = new Double[len];

for (int index = 0; index < len; index++)
    boxedArray[index] = Double.valueOf(primitiveArray[index]);
like image 133
fge Avatar answered Oct 22 '22 09:10

fge