Add a custom cast?

Hi I’m making a math library and it includes a matrix class.
I wish to make it possible to cast it from a float[][]. Something like this:

float[][] a={{1,2},{3,4}};
Matrix m=(Matrix) a;

Can’t you just create a static method (or alt. an overloaded constuctor) which converts a float[][] to a Matrix, like static final Matrix.fromFloatArray2d(final float[][] arr2d) {}? :bulb:

I put that into my Matrix class and it says that there is no return type. Could you please explain how this method works.

When developing a library and you want others to take a look you should make it available online on some repo: :sunglasses:

I’ll do so but I have to add a few comments. (remove actully I have lots of usless Code wich is just commented)

Edit 2: I’m done The Library

So how can I add a cast from a float[][] to my Matrix class?

1 Like

It would be a function outside the class or inside the class like

Matrix getMatrix(float [][] grid) {
//do magic
return resultMatrix;

}

As has been said above

You can also make a constructor and use it in my function. Which is not a cast but converter

I’ve already added a overloaded constructor. But to create a Matrix object I have to do something like this:

Matrix m=new Matrix(arr2d);

but a cast would be much easier.

Unfortunately Java only allows (cast) among compatible datatypes.
That is, they have a parent/child datatype relationship.

Well, now you can also add an alternative static method for that same conversion functionality:

final float[][] f = { { 1, 2 }, { 3, 4 } };
Matrix m;

void setup() {
  m = new Matrix(f);
  println(m);

  m = Matrix.fromFloatArray2d(f);
  println(m);

  exit();
}

static // Comment this out when inside a ".java" file!!!
public class Matrix {
  public float[][] matrix;
  public int rows, cols;

  public Matrix(final float[][] m) {
    rows = m.length;
    cols = m[0].length;
    matrix = m.clone();
    for (int i = 0; i < rows; matrix[i] = m[i++].clone());
  }

  static public final Matrix fromFloatArray2d(final float[][] m) {
    return new Matrix(m);
  }

  @Override public String toString() {
    final StringBuilder s = new StringBuilder("rows x cols (");
    s.append(rows).append(" x ").append(cols).append("):\n");

    for (int i = 0; i < rows; ++i)
      s.append(java.util.Arrays.toString(matrix[i])).append('\n'); 

    return s.toString();
  }
}
1 Like