0

I'm using Apache math library for matrices and one here's one of the methods I'm trying to use:

MatrixUtils.createRealDiagonalMatrix(double[] diagonal)

I don't know the size at compilation time so I'm using ArrayList<Double> to store the diagonal and later I want to pass that as parameter to the above function. How can I cast the ArrayList to double[] ? I've tried:

ArrayList<Double> arr = new ArrayList<Double>(n);
... // Populate arr
MatrixUtils.createRealDiagonalMatrix(arr.toArray(new Double[n]));

But I'm getting a type mismatch error since Double[] and double[] are different.

Shmoopy
  • 5,020
  • 3
  • 31
  • 68

2 Answers2

2

You can use ArrayUtils.toPrimitive(double[]):

double[] diagonal = ArrayUtils.toPrimitive(arr.toArray(new Double[arr.size()]));
arshajii
  • 123,543
  • 24
  • 232
  • 276
1

If you can use 3rd party libraries, I'd suggest you to give guava library a try. It has plenty of useful features, and your case can be dealt in the following way:

List<Double> data = new ArrayList<Double>(); // your data
MatrixUtils.createRealDiagonalMatrix(Doubles.toArray(data));

See javadoc for reference.

Andrew Logvinov
  • 20,025
  • 4
  • 51
  • 53