Brian Brian - 8 months ago 44
Java Question

How do I convert Double[] to double[]?

I'm implementing an interface that has functionality similar to a table that can contain an types of objects. The interface specifies the following function:

double[] getDoubles(int columnIndex);

Where I'm stumped is that in my implementation, I'm storing the table data in a 2D
array (
Object[][] data
). When I need to return the values, I want to do the following (it is assumed that
will only be called on a column that contains doubles, so there will be no

double[] getDoubles(int columnIndex) {
return (double[]) data[columnIndex];

But - Java doesn't allow
to be cast to
. Casting it to
is ok because
is an object and not a primitive, but my interface specifies that data will be returned as a

So I have two questions:

  1. Is there any way I can get the column data out of the
    table and return the array of primitives?

  2. If I do change the interface to return
    , will there be any performance impact?

Answer Source

Unfortunately you will need to loop through the entire list and unbox the Double if you want to convert it to a double[].

As far as performance goes, there is some time associated with boxing and unboxing primitives in Java. If the set is small enough, you won't see any performance issues.