converting Object [] to double [] in java
Solution 1
The non-generic toArray
might not be optimal, I'd recommend you to use a for
loop instead:
Long[] v = new Long[entry.getValue().singleValues.size()];
int i = 0;
for(Long v : entry.getValue().singleValues) {
v[i++] = v;
}
Now you've got an array of Long
objects instead of Object
. However, Long
is an integral value rather than floating-point. You should be able to cast, but it smells like an underlying problem.
You can also convert directly instead of using a Long
array:
double[] v = new double[entry.getValue().singleValues.size()];
int i = 0;
for(Long v : entry.getValue().singleValues) {
v[i++] = v.doubleValue();
}
Concept: you must not try to convert the array here, but instead convert each element and store the results in a new array.
Solution 2
In order to "convert" an array of type Object[]
to double[]
you need to create a new double[]
and populate it with values of type double
, which you'll get by casting each Object
from the input array separately, presumably in a loop.
user2007843
Updated on June 09, 2022Comments
-
user2007843 almost 2 years
Is this possible? I have been struggling with this for a while. I was originally casting to
Long []
first and then converting todouble []
which let me compile but then gave me an error for the casting. I am now stuck.In this code, I am iterating over the entries in my hashmap.
Object[] v = null; for(Map.Entry<String,NumberHolder> entry : entries) { v = entry.getValue().singleValues.toArray(); //need to get this into double [] }
Here is my numberHolder class
private static class NumberHolder { public int occurrences = 0; public ArrayList<Long> singleValues = new ArrayList<Long>(); }
-
yshavit about 11 yearsOr just
v.doubleValue()
, since Long instanceof Number. -
user2007843 about 11 yearsI have to use the array because I am making a graph and the method
dataset.addSeries
only acceptsdouble []
-
CsBalazsHungary about 11 years@user2007843 I see, I still recommend to make a converter instead of doing the job locally.