Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Object array (Object[][] data). When I need to return the values, I want to do the following (it is assumed that getDoubles() will only be called on a column that contains doubles, so there will be no ClassCastExceptions):

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

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

So I have two questions:

  1. Is there any way I can get the column data out of the Object[][] table and return the array of primitives?
  2. If I do change the interface to return Double[], will there be any performance impact?
like image 352
Brian Avatar asked Jul 10 '09 14:07

Brian


People also ask

How do you convert double to double?

To convert double primitive type to a Double object, you need to use Double constructor. Let's say the following is our double primitive. // double primitive double val = 23.78; To convert it to a Double object, use Double constructor.

How do you convert an object to a double value?

There are three ways to convert a String to double value in Java, Double. parseDouble() method, Double. valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time.


2 Answers

If you don't mind using a 3rd party library, commons-lang has the ArrayUtils type with various methods for manipulation.

Double[] doubles; ... double[] d = ArrayUtils.toPrimitive(doubles); 

There is also the complementary method

doubles = ArrayUtils.toObject(d); 

Edit: To answer the rest of the question. There will be some overhead to doing this, but unless the array is really big you shouldn't worry about it. Test it first to see if it is a problem before refactoring.

Implementing the method you had actually asked about would give something like this.

double[] getDoubles(int columnIndex) {     return ArrayUtils.toPrimitive(data[columnIndex]); } 
like image 130
Rich Seller Avatar answered Oct 09 '22 19:10

Rich Seller


In Java 8, this is one-liner:

Double[] boxed = new Double[] { 1.0, 2.0, 3.0 }; double[] unboxed = Stream.of(boxed).mapToDouble(Double::doubleValue).toArray(); 

Note that this still iterates over the original array and creates a new one.

like image 20
Infeligo Avatar answered Oct 09 '22 20:10

Infeligo