0

I want to store LinkedHashMap value into double type array. How to do that ?

I tried in this way

 Double[] avg=  (Double[]) averageMap.values().toArray();

where averageMap is:

LinkedHashMap<String, Double> averageMap = new LinkedHashMap<String, Double>();

but I have the following exception :

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Double;
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
SRY_JAVA
  • 323
  • 3
  • 10
  • 21

2 Answers2

1

The toArray function might be a bit complicated. It returns an Object[] which cannot be cast to Double[]. You have to use this code snippet instead:

Collection<Double> values = averageMap.values();
Double[] avg = values.toArray(new Double[values.size()]);
Seelenvirtuose
  • 20,273
  • 6
  • 37
  • 66
0

Below code will work for you but its not good enough

        Object[] objArray = averageMap.values().toArray();
        double[] dblArray = new double[objArray.length];
        for (int i = 0; i < objArray.length; i++) {
            dblArray[i] = Double.parseDouble(objArray[i].toString());
        }

averageMap.values().toArray(); method returns object[] so you have to cast it to Double or pars it to double[]

but its not good practice to parse it to double.instead of double use Double class.it is wrapper class so autoboxing done automatically so no need to worry

Nirav Prajapati
  • 2,987
  • 27
  • 32
  • I have to finally store the value of LinkedHaspMap into double type of array i.e primitive type as this value will be used further into ChartDirector.XYChart method which takes primitive type arguments. – SRY_JAVA Nov 10 '14 at 10:23
  • than try this one its work for you – Nirav Prajapati Nov 10 '14 at 10:25