Reputation: 609
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>();
}
Upvotes: 6
Views: 13573
Reputation: 813
This smells a bit as some bad practice.
First of all, I discourage you to use arrays, use Map or List.
If you need the values as double, make a getter which
private List<Long> myList;
//initialize somewhere
double getElementAsDouble(int index){
return myList.get(index).doubleValue();
}
And add a converter like getMyListAsDoubleArray() where you make the conversion if you really have to use Array. You can check out the solution from the answers here, for example Matthias Meid's.
Upvotes: 0
Reputation: 12523
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.
Upvotes: 7
Reputation: 26184
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.
Upvotes: 2