Convert object [] to double [] in java

Is it possible? I struggled with this for a while. First, I swung to Long [] , and then converted to double [] , which allowed me to compile, but then gave me an error for casting. I'm stuck right now.

In this code, I repeat 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 class numberHolder

 private static class NumberHolder { public int occurrences = 0; public ArrayList<Long> singleValues = new ArrayList<Long>(); } 
+4
source share
3 answers

A non-generic toArray may not be optimal, I would recommend using 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 have an array of Long objects instead of Object . However, Long is an integral value, not a floating point. You should be able to throw, but it smells like a major problem.

You can also convert directly instead of the 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 should not try to convert the array here, but instead convert each element and save the results in a new array.

+7
source

To "convert" an array of type Object[] to double[] , you need to create a new double[] and fill it with values ​​of type double , which you will get by typing each Object from the input array separately, presumably in a loop.

+2
source

It smells a bit like bad practice.
First of all, I am preventing you from using arrays, using Map or List.

If you need values ​​like double, make getter which

 private List<Long> myList; //initialize somewhere double getElementAsDouble(int index){ return myList.get(index).doubleValue(); } 

And add a converter such as getMyListAsDoubleArray () where you do the conversion if you really need to use Array. You can check the solution from the answers here, for example, Matthias Meid's.

0
source

All Articles