Is this possible? I have been struggling with this for a while. I was originally casting to Long []
first and then converting to double []
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>();
}
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.
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.
We can convert String to double in java using Double. parseDouble() method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With