Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting Object [] to double [] in java

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>();
}
like image 749
user2007843 Avatar asked Apr 22 '13 13:04

user2007843


People also ask

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.

How do you create a double object in java?

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 I convert a String to a double in java?

We can convert String to double in java using Double. parseDouble() method.


1 Answers

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.

like image 60
Matthias Meid Avatar answered Sep 20 '22 04:09

Matthias Meid