converting Object [] to double [] in java

arrays, double, java, object

Solution

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.

Problem

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>(); } ```

Original source