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,334
  • 4
  • 36
  • 72

2 Answers2

2

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

double[] diagonal = ArrayUtils.toPrimitive(arr.toArray(new Double[arr.size()]));
arshajii
  • 127,459
  • 24
  • 238
  • 287
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
  • 21,181
  • 6
  • 52
  • 54